首先写一个RabbitMQ的配置类,可以点对点的形式注入Queue,也可以用交换机的形式
package com.moon.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
@Bean
public Queue XukeQ(){
return new Queue("XukeQ");
}
@Bean
public Queue QuzheQ() {
return new Queue("QuzheQ");
}
@Bean
public FanoutExchange liShenExchange(){
return new FanoutExchange("liShenExchange");
}
@Bean
public DirectExchange DingJianJunExchange() {
return new DirectExchange("DingJianJunExchange");
}
//定义绑定关系
@Bean
public Binding bindQuzheQToliShenExchange(){
return BindingBuilder.bind(XukeQ()).to(liShenExchange());
}
@Bean
public Binding bindQuzheQToliShenExchange2(){
return BindingBuilder.bind(QuzheQ()).to(liShenExchange());
}
@Bean
public Binding bindQuzheQToliShenExchange3(){
return BindingBuilder.bind(XukeQ()).to(DingJianJunExchange()).with("aaa");
}
@Bean
public Binding bindQuzheQToliShenExchange4(){
return BindingBuilder.bind(XukeQ()).to(DingJianJunExchange()).with("nnn");
}
}
然后是在controller发送消息及接受消息的代码详解
package com.moon.controller;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mq")
public class MqController {
@Autowired
private RabbitTemplate rabbitTemplate;
@RequestMapping("/addToQ")
public String addToQ(String task){
rabbitTemplate.convertAndSend("DingJianJunExchange","nnn", task);
return "success";
}
@RequestMapping("/getFromQ")
public String getFromQ(String task){
String xukeQ = rabbitTemplate.receiveAndConvert("liShenExchange").toString();
return xukeQ;
}
}
配置一个监听器
package com.moon.listener;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class XuKeQlistener {
@Value("${moon.proj.name}")
private String name;
@RabbitListener(queues="XukeQ")
public void onMsg(String task){
System.out.println(name+":222"+task);
}
@RabbitListener(queues="QuzheQ")
public void onMsg1(String task){
System.out.println(name+":"+task);
}
}