zoukankan      html  css  js  c++  java
  • RabbitMQ消息分发模式

    RabbitMQ 默认采用轮询的方式分发消息,当一个消息需要有多个消费者都消费时,需要创建多个队列实现,示例如下:

    @Component
    public class SimpleConsume {
    
        @RabbitListener(
                bindings =
                @QueueBinding(
                        value = @Queue(durable = "true"), // 不指定队列名称,系统会自动生成队列名
                        exchange = @Exchange(value = "simpleExchange",
                                type = "topic"),
                        key = "simple.*"
                )
        )
        public void onMessage(Message message, Channel channel) throws Exception {
            System.err.println("--------------------------------------");
            System.err.println("消费端Payload: " + message.getPayload());
            Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            //手工ACK
            channel.basicAck(deliveryTag, false);
        }
    
    }
    
    @SpringBootTest
    public class Producer {
        @Autowired
        private RabbitTemplate rabbitTemplate;
        
    	@Test
        public void sendSimpleMessage() {
            String exchange = "simpleExchange";
            String routingKey = "simple.message";
            for(int i=0;i<5;i++) {
                rabbitTemplate.convertAndSend(exchange, routingKey, "hello simpleExchange ===="+ i);
            }
        }
    }    
    

    启动两个端口不同的项目:执行 sendSimpleMessage 方法,查看控制台输出:

    端口 8080 控制台:

    --------------------------------------
    消费端Payload: hello simpleExchange ====0
    --------------------------------------
    消费端Payload: hello simpleExchange ====1
    --------------------------------------
    消费端Payload: hello simpleExchange ====2
    --------------------------------------
    消费端Payload: hello simpleExchange ====3
    --------------------------------------
    消费端Payload: hello simpleExchange ====4
    

    端口 8081 控制台:

    --------------------------------------
    消费端Payload: hello simpleExchange ====0
    --------------------------------------
    消费端Payload: hello simpleExchange ====1
    --------------------------------------
    消费端Payload: hello simpleExchange ====2
    --------------------------------------
    消费端Payload: hello simpleExchange ====3
    --------------------------------------
    消费端Payload: hello simpleExchange ====4
    

    可以看到两个消费者都可以消费到所有消息了。

  • 相关阅读:
    java内存管理的一些基础,内存溢出的解决方案
    设计模式中类的关系 .
    一个很郁闷的问题,Java中的僵死进程
    quartzscheduler的集群化配置
    转 : 敏捷开发的原则 .
    如何进行单元测试
    欢迎来到地狱 WriteUp(2019暑假CTF第一周misc)
    20181218小黄衫获得感想和阶段性总结
    2019暑假Java学习笔记(一)
    2019“嘉韦思杯”3.30初赛一部分Write Up
  • 原文地址:https://www.cnblogs.com/markLogZhu/p/13564737.html
Copyright © 2011-2022 走看看