How to Achieve Concurrency With a Non-Thread-Safe MessageListener

折月煮酒 提交于 2019-12-01 06:31:36

It's generally best practice to use stateless beans for listeners but when that's not possible, to configure @Prototype scope listener (and multiple containers) using only Java Configuration, you can use:

@Bean
public SimpleMessageListenerContainer container1() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
    container.setQueueNames("test.mismatch");
    container.setMessageListener(new MessageListenerAdapter(listener()));
    container.setMismatchedQueuesFatal(true);
    return container;
}

...

@Bean
public SimpleMessageListenerContainer containerN() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
    container.setQueueNames("test.mismatch");
    container.setMessageListener(new MessageListenerAdapter(listener()));
    container.setMismatchedQueuesFatal(true);
    return container;
}

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MyNotThreadSafeListener listener() {
    return new MyNotThreadSafeListener();
}

Remember that any dependencies injected into MyNotThreadSafeListener must also be prototype beans.

Bottom line is stateless beans are best.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!