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
    

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

  • 相关阅读:
    MVC3、如何应用EntityFramework 连接MySql 数据库 Kevin
    DEV EXPRESS Summary Footer 不显示 Kevin
    装饰模式 Kevin
    Dev 控件 GridControl 控件 二次绑定数据源的问题。 Kevin
    System.InvalidOperationException 异常 Kevin
    LINQ to XML Kevin
    代理模式——代码版“吊丝的故事” Kevin
    VS2012 中的设备 面板 Kevin
    maven 学习笔记(三)创建一个较复杂的 eclipse+android+maven 工程
    maven 学习笔记(一)eclipse+android+maven
  • 原文地址:https://www.cnblogs.com/markLogZhu/p/13564737.html
Copyright © 2011-2022 走看看