如何在Spring Boot中创建/配置自己的AMQP ContainerFactory?

时间:2019-03-13 17:45:45

标签: spring-boot spring-amqp

我添加了此内容是为了尝试创建和配置自己的SimpleRabbitListenerContainerFactory以替换默认值

@Bean
open fun myFactory(cf: ConnectionFactory): SimpleRabbitListenerContainerFactory {
    val factory = SimpleRabbitListenerContainerFactory()
    factory.setConnectionFactory(cf)
    factory.setDefaultRequeueRejected(false)
    factory.setAfterReceivePostProcessors(MessagePostProcessor {
        it.messageProperties.contentType = MediaType.APPLICATION_JSON_VALUE
        return@MessagePostProcessor it
    })
    return factory
}

代码运行时,我仍然看到

o.s.a.r.listener.BlockingQueueConsumer   : Rejecting messages (requeue=true)

这使我相信Spring Boot没有使用我的ContainerFactory。我想如果我可以正确配置它,我并不在乎它是否在使用我的。解决此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

请参见the documentation

除非您在注释上设置rabbitListenerContainerFactory属性,否则默认情况下框架会查找名为containerFactory的工厂。

  

默认情况下,基础架构会寻找一个名为rabbitListenerContainerFactory的bean作为工厂的源,以用于...

要覆盖Boot的bean,将其命名为rabbitListenerContainerFactory

这样做时,通常最好使用配置器,以便您的启动属性将被应用...

@Bean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(
        SimpleRabbitListenerContainerFactoryConfigurer configurer,
        ConnectionFactory connectionFactory) {

    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    configurer.configure(factory, connectionFactory);

    factory.setDefaultRequeueRejected(false)
    factory.setAfterReceivePostProcessors(MessagePostProcessor {
        it.messageProperties.contentType = MediaType.APPLICATION_JSON_VALUE
        return@MessagePostProcessor it
    })

    return factory;
}