如何添加一个额外的监听器来监听 Spring AMQP 队列?

How to add an additional Listener to listen to queue with Spring AMQP?

我目前有一个 FooListener 侦听包含 Foo 消息的队列。如何添加另一个 BarListener class 以收听同一队列的 Bar 消息?

我的 RabbitMQ 当前配置如下:

@Configuration
public class RabbitMQConfig {
    @Bean
    public MessageListenerContainer messageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueues(workQueue());
        container.setMessageListener(new MessageListenerAdapter(fooListener(), new JsonMessageConverter()));
        container.setDefaultRequeueRejected(false);
        return container;
    }
}

目前没有内置支持根据负载类型路由到不同的侦听器。

您可以编写一个简单的侦听器包装器...

public void handleMessage(Object payload) {
    if (payload instanceof Foo) {
        this.fooListener.handleMessage((Foo) payload);
    }
    else if (payload instanceof Bar) {
        this.barListener.handleMessage((Bar) payload);
    }
    else {
        // unexpected payload type
    }
}

编辑:

Spring AMQP 1.5(目前处于里程碑 1 - 1.5.0.M1)现在支持此功能;参见 what's new and blog announcement

我认为对不同的消息使用相同的队列不是最好的选择。

您可以使用两个路由键进行一次交换,并使用两个队列进行不同的绑定。另一种方法是像 Gary Russell 所说的那样使用包装器,但是铸件没有很好的性能,而且这个解决方案不是很 "Single responsibility principle".

此致。