目录
2. 在 application.yml 中配置rabbitmq的 连接信息:
可见,消费者1消费了5个奇数消息,消费者2消费了5个偶数消息
1.先加入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 在 application.yml 中配置rabbitmq的 连接信息:
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
listener:
simple:
acknowledge-mode: manual
prefetch: 1
3.创建生产者
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendRoutingType(String msg,String key){
//参数:1-交换机 2-路由键 3-发送的信息
this.amqpTemplate.convertAndSend("hello.exchange.direct",key,msg);
}
}
4.创建两个消费者
第一个
@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
//指定绑定的队列(该队列将自动创建),autoDelete="true"意味着程序关闭时该队列自动删除
value = @Queue(value = "hello.direct.queue-1",autoDelete = "true"),
//指定交换机,交换机类型:direct(默认)
exchange = @Exchange(value = "hello.exchange.direct"),
//队列与交换机绑定的路由键,带有此路由键的消息会被交换机发送到该队列
key = "hello.queue.1"
))
public class RoutingReceiver1 {
@SneakyThrows
@RabbitHandler
public void process(String msg, Channel channel, Message message){
log.info("RoutingReceiver1 = {}",msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
第二个
@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
//指定绑定的队列(该队列将自动创建),autoDelete="true"意味着程序关闭时该队列自动删除
value = @Queue(value = "hello.direct.queue-2",autoDelete = "true"),
//指定交换机,交换机类型:direct(默认)
exchange = @Exchange(value = "hello.exchange.direct"),
//队列与交换机绑定的路由键,带有此路由键的消息会被交换机发送到该队列
key = "hello.queue.2"
))
public class RoutingReceiver2 {
@SneakyThrows
@RabbitHandler
public void process(String msg, Channel channel, Message message){
log.info("RoutingReceiver2 = {}",msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
5.测试类中测试
@SpringBootTest
class Rabbitmt1ApplicationTests {
@Autowired
private Sender sender;
@Test
void sendRoutingType() throws Exception{
for (int i=0; i<10; i++){
//偶数往2里发,奇数往1里发
String key = i%2==0 ? "hello.queue.2":"hello.queue.1";
sender.sendRoutingType("hello-"+i,key);
}
}
}