概要:
rabbitmq中,一个queue可以绑定多个routingkey,一个routingkey可以绑定多个queue。(下面demo演示的是一个queue可以绑定多个routingkey)
application.properties配置:
spring.rabbitmq.host=localhost
# TCP/IP端口为5672,http端口为15672
spring.rabbitmq.port=5672
spring.rabbitmq.username=root
spring.rabbitmq.password=root
生产者:
package com.example.rabbitmq;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RabbitMQController {
// 这里用的是RabbitTemplate发消息,也可以用AmqpTemplate,推荐使用RabbitTemplate。
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping(value = "/helloRabbit3")
public String sendMQ3(){
rabbitTemplate.convertAndSend("myExchange1", "routingKey1","多重绑定");
rabbitTemplate.convertAndSend("myExchange1", "routingKey2","多重绑定");
rabbitTemplate.convertAndSend("myExchange1", "routingKey3","多重绑定");
return "success";
}
}
消费者:
package com.example.rabbitmq;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "myQueue4"),
exchange = @Exchange(value = "myExchange1"),
key = {"routingKey1", "routingKey2", "routingKey3"}
)
)
public void process4(Message message){
System.out.println("myQueue4:" + new String(message.getBody()));
}
}
启动项目,访问http://localhost:8080/helloRabbit3,控制台打印
myQueue4:多重绑定
myQueue4:多重绑定
myQueue4:多重绑定