springboot-rabbitmq之工作队列(二)
2020-11-08 本文已影响0人
前进的码农
概念
老样子还是先上图

生产者p 把消息发送到队列其实是先发送到默认的路由,如果有多个消费者消费的话,消息会按照轮询的模式挨个的分发给消费者进行消费
代码
生产端
@Component
@Data
public class MyBean {
private final AmqpAdmin amqpAdmin;
private final AmqpTemplate amqpTemplate;
@Autowired
public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
this.amqpAdmin = amqpAdmin;
this.amqpTemplate = amqpTemplate;
}
@Bean
Queue queue(){
return QueueBuilder.durable("hello").build();
}
}
这里模拟发送10条消息
@Autowired
MyBean myBean;
@Test
void test(){
for (int i = 0; i <10 ; i++) {
myBean.getAmqpTemplate().convertAndSend("hello","queues:"+i);
}
}
代码和上个案列的差不多
消费端
这里模拟2个消费端,所以启动2个springboot 实列
@Component
@Slf4j
public class ReceiverBean {
@RabbitListener(queues = "hello")
public void processMessage(String msg) {
log.info("i am consumer 01---"+msg);
}
}
@Component
@Slf4j
public class ReceiverBean {
@RabbitListener(queues = "hello")
public void processMessage(String msg) {
log.info("i am consumer msg---"+msg);
}
}
结果


每个消费者消费了5条消息,是不是很公平。
代码
生产者
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-queues-producer
消费者
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-queues-consumer
消费者
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-queues-consumer-01