1. 程式人生 > 實用技巧 >RabbitMQ訊息分發模式

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

可以看到兩個消費者都可以消費到所有訊息了。