spring ampq annotation驱动一个队列两个侦听器区分路由键

时间:2017-01-23 22:47:39

标签: java rabbitmq spring-annotations spring-amqp

实际上我没有这样运行。也许我误解了一些事情,无论如何这是不可能的。我试图在同一个队列上配置2个侦听器,相同的交换但只有路由键应该不同。我的问题是不知何故事情搞砸了。结果是监听器A获取了用于监听器B的消息。但有时只有一切,有时一切正常。有什么建议吗?

的myconfig

@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(getHostname());
    connectionFactory.setUsername(getUsername());
    connectionFactory.setPassword(getPassword());
    return connectionFactory;
}

@Bean
public RabbitAdmin rabbitAdmin() {
    return new RabbitAdmin(connectionFactory());
}

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setMessageConverter(new CustomMessageConverter());
    factory.setConnectionFactory(connectionFactory());
    factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
    factory.setConcurrentConsumers(10);
    factory.setMaxConcurrentConsumers(10);
    return factory;
}

@Override
public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
    registrar.setMessageHandlerMethodFactory(myHandlerMethodFactory());
}

@Bean
public DefaultMessageHandlerMethodFactory myHandlerMethodFactory() {
    DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
    factory.setMessageConverter(new MappingJackson2MessageConverter());
    return factory;
}

MyListeners A

@RabbitListener(bindings = @QueueBinding(value = @Queue(value = QUEUE, durable = "true"), exchange = @Exchange(value = EXCHANGE, type = "topic", durable = "true", ignoreDeclarationExceptions = "true"), key = "routingKeyA"))
public String myListenerA(@Payload PayloadA payload, @Header(AmqpHeaders.CORRELATION_ID) byte[] correlationId) { 

    return SUCCESS_RESPONSE;
}

MyListener B

@RabbitListener(bindings = @QueueBinding(value = @Queue(value = QUEUE, durable = "true"), exchange = @Exchange(value = EXCHANGE, type = "topic", durable = "true", ignoreDeclarationExceptions = "true"), key = "routingKeyB"))
public String myListenerB(@Payload PayloadB payload, @Header(AmqpHeaders.CORRELATION_ID) byte[] correlationId) { 

    return SUCCESS_RESPONSE;
}

其他信息:此队列中有20位消费者。 Thx提前!

1 个答案:

答案 0 :(得分:1)

RabbitMQ不会这样做;与JMS不同,无法从队列中选择消息(例如,基于路由密钥)。

您所做的就是使用2个不同的路由键将相同的队列绑定到交换机。所以,是的,任何一个监听器都会收到消息,无论它是如何进入队列的。

使用RabbitMQ,每个侦听器都需要一个单独的队列。当生产者发布到交换机时,代理将根据他使用的路由密钥将消息路由到正确的队列。

如果每个侦听器都有多个实例,则将相应地分发消息(每个队列只传递一个)。