接收方:
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
@Configuration
public class RabbitConfig {
@Bean
public Queue showqa_label(){
return new Queue("showqa_label");
}
@Bean
public Queue showAll(){
return new Queue("showAll");
} }
4:编写接收的方法
@Component
public 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:编写发送消息的方法
@Component
public 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方法即可。
|