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
    

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

  • 相关阅读:
    教师派10
    教师派9
    简单理解socket(AF_INET&SOCK_STREAM,SOCK_DGRAM)
    Deepin安装MySQL(MariaDB)不提示设置密码问题(密码为空)
    经典排序算法-附python代码
    Linux虚拟环境virtualevn
    linux安装虚拟环境
    deepin安装虚拟环境virtualenv
    deepin安装虚拟环境virtualenv
    把握AFNet网络请求完成的正确时机
  • 原文地址:https://www.cnblogs.com/markLogZhu/p/13564737.html
Copyright © 2011-2022 走看看