gpt4 book ai didi

java - 当rabbit最初关闭时,Bean无法初始化

转载 作者:太空宇宙 更新时间:2023-11-04 13:52:53 25 4
gpt4 key购买 nike

org.springframework.web.context.ContextLoader | localhost-startStop-1 |     Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'simpleListenerContainer' defined
 in class path resource [com/company/product/api/config/amqp/InternalAmqpConfiguration.class]: Bean instantiation v
ia factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate

如果在我的 Spring MVC 应用程序启动之前 Rabbit 已关闭,则依赖于 CachingConnectionFactory 的许多 Bean 将无法初始化。就像下面这样:

 @Autowired
@Bean
public SimpleRabbitListenerContainerFactory simpleistenerContainer(
@Qualifier("internal") CachingConnectionFactory connectionFactory,
RabbitAdmin admin) {

for(Listeners listener : Listeners.values()) {
Queue q = new Queue(listener.queue, true, true, true);
admin.declareQueue(q);
admin.declareBinding(
BindingBuilder.bind(q)
.to(new TopicExchange(listener.exchange, true, false))
.with((listener.appendWildcard) ? listener.routingKey + ""
+ ".*" : listener.routingKey)
);
}

SimpleRabbitListenerContainerFactory listenerContainerFactory = new
SimpleRabbitListenerContainerFactory();

listenerContainerFactory.setConnectionFactory(connectionFactory);

return listenerContainerFactory;
}

此操作失败并且无法恢复,因为缺少此依赖项之一而导致 Bean 未初始化。我考虑过在 CachingConnectionFactory 上设置 ConnectionListener,但这些对象将无法作为 bean 访问。任何的意见都将会有帮助。我确信可能有一个简单的解决方案。

最佳答案

只需将您的绑定(bind)等添加为 @Bean,而不是自己声明它们。

添加一个RabbitAdmin @Bean,它会在建立连接时自动执行声明。

编辑:

回应您的评论...

但是,您正在执行自己的声明:

admin.declareQueue(q);
admin.declareBinding(...

如果代理不可用,除非您添加 try/catch,否则这些操作将会失败。您还可以在管理员上设置 ignoreDeclarationExceptions,但您实际上不需要自己执行这些声明。一旦容器建立连接,管理员就会自动声明它们。

编辑2:

Why would they get declared? ...

因为这就是它的设计方式;请阅读the documentation向下滚动查看Binding等的java配置

RabbitAdmin(如果在上下文中声明)将自身注册为连接监听器。建立连接后,管理员会在上下文中查找所有 QueueExchangeBinding @Bean,并在建立连接时声明它们。

您通过直接从 bean 定义进行绑定(bind)来破坏此“惰性”声明,这要求代理可用,并且如果没有连接,上下文将无法初始化。

只需在上下文中声明您所需的Binding,管理员就会在代理可用时为您处理。监听器容器将根据其 recoveryInterval 继续尝试连接,并且最终成功时将发生声明。

关于java - 当rabbit最初关闭时,Bean无法初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30130034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com