@Configuration
public class RabbitConfig {
@Bean
public Queue helloQueue(){
return new Queue("hello");
}
producer
@Component
public class HelloSender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send(){
String context = "hello " + new Date();
System.out.println("Sender : "+ context);
this.rabbitTemplate.convertAndSend("hello", context);
}
consumer
@Component
@RabbitListener(queues = "hello")
public class HelloReceiver {
@RabbitHandler
public void process(String hello){
System.out.println("Receiver : " + hello);
}
测试类
@SpringBootTest
public class Test {
@Autowired
private HelloSender helloSender;
@org.junit.jupiter.api.Test
void contextLoads(){
helloSender.send();
}
运行结果
image.png
Topic exchange
Config
@Configuration
public class TopicRabbitConfig {
final static String message = "topic.message";
final static String messages = "topic.messages";
* 创建队列
* @return
@Bean
public Queue queueMessage() {
return new Queue(TopicRabbitConfig.message);
* 创建队列
* @return
@Bean
public Queue queueMessages() {
return new Queue(TopicRabbitConfig.messages);
* 将对列绑定到Topic交换器
* @return
@Bean
TopicExchange exchange() {
return new TopicExchange("topicExchange");
* 将queueMessage队列绑定到Topic交换器并监听为topic.message的routingKey
* 也就是说,当你发送消息时的key为topic.message的话,他就会被投递到queueMessage队列中,这个队列名字需要与上面声明的方法名相同
* public Queue queueMessage() {
* return new Queue(TopicRabbitConfig.message);
* }
* @param queueMessage
* @param exchange
* @return
@Bean
Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) {
return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");
* 将队列绑定到Topic交换器 采用#的方式,与上述方法类似,只是本处采用通配符。也就是说,所有以topic.开头的消息都会被投递到queueMessages队列中
* @param queueMessages
* @param exchange
* @return
@Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
}
producer
@Component
public class TopicSender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send1() {
String context = "hi, i am message 1";
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("topicExchange", "topic.message", context);
public void send2() {
String context = "hi, i am messages 2";
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("topicExchange", "topic.ffsda", context);
}
Consumer
@Component
@RabbitListener(queues = "topic.message")
public class TopicReceiver {
@RabbitHandler
public void process(String message) {
System.out.println("Topic Receiver1 : " + message);
}
Consumer2
@Component
@RabbitListener(queues = "topic.messages")
public class TopicReceiver2 {
@RabbitHandler
public void process(String message) {
System.out.println("Topic Receiver2 : " + message);
}
测试类
@SpringBootTest
public class Test {
@Autowired
private TopicSender topicSender;
@org.junit.jupiter.api.Test
public void send1() {
topicSender.send1();
@org.junit.jupiter.api.Test
public void send2() {
topicSender.send2();
}