spring boot中用RabbitMQ调用接口

来源:互联网 发布:发票查询真伪软件 编辑:程序博客网 时间:2024/06/03 06:46

接收方:

1:在配置文件中配置rabbitmq

rabbitmq:      host: 127.0.0.1      port: 5672      username: guest      password: guest      publisher-confirms: true

2:在pom.xml添加需要的依赖

<dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-amqp</artifactId></dependency>


3:创建新的Queue

@Configurationpublic class RabbitConfig {    @Bean    public Queue showqa_label(){        return new Queue("showqa_label");    }
    @Bean    public Queue showAll(){       return new Queue("showAll");    }
}
4:编写接收的方法

@Componentpublic class Receiver {    @Autowired    ShowQaService showQaService;    @RabbitListener(queues = "showqa_label")    @RabbitHandler
    public String process(){        BaseResponse baseResponse = new BaseResponse();        List<Map<String, Object>> list = showQaService.showqa_label();        baseResponse.setData(list);        return ObjectUtils.toJSON(baseResponse);//返回给发送方    }
    @RabbitListener(queues = "showAll")    @RabbitHandler    public String showAll(String str){       ShowRequest showRequest = JSON.parseObject(str, ShowRequest.class);       BaseResponse baseResponse = new BaseResponse();       String result = showQaController.showall(showRequest);//返回给发送方       return result;    }
}
发送方:
前两步同接收方一样
3:编写发送消息的方法
@Componentpublic class Sender {    @Autowired    private AmqpTemplate amqpTemplate;    public String showqa_label(){        String result =  amqpTemplate.convertSendAndReceive("showqa_label", "").toString();        return result;    }
    public String showAll(Map<String, Object> map){        String str = JSON.toJSONString(map);        String result = amqpTemplate.convertSendAndReceive("showAll", str).toString();        return result;     }
}
4:在需要的地方创建Sender类,调用showqa_label、showAll方法即可。




原创粉丝点击