現在我正在研究包含多個組件的Spring應用程序,其中包括一個RabbitMQ組件。確保運行Spring應用程序的其餘部分,即使在運行時有一個bean有錯誤
RabbitMQ連接的初始化是通過配置bean在應用程序啓動時自動變爲活動的。
下面是我的RabbitMQ配置文件:
@Configuration
@PropertySources({
@PropertySource("classpath:message.properties"),
@PropertySource("classpath:rabbitmq.properties")
})
@EnableRabbit
public class MessageConfiguration {
private static final String MESSAGE_HOST_PROPERTY = "message.host";
private static final String FACTORY_USERNAME_PROPERTY = "rabbitmq.username";
private static final String FACTORY_PASSWORD_PROPERTY = "rabbitmq.password";
private Environment environment;
@Autowired
public MessageConfiguration(Environment environment) {
this.environment = environment;
}
@Bean
public AmqpTemplate publishTemplate() {
RabbitTemplate result = new RabbitTemplate(connectionFactory());
return result;
}
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(environment.getProperty(MESSAGE_HOST_PROPERTY));
connectionFactory.setUsername(environment.getProperty(FACTORY_USERNAME_PROPERTY));
connectionFactory.setPassword(environment.getProperty(FACTORY_PASSWORD_PROPERTY));
return connectionFactory;
}
}
在Bean connectionFactory的,如果我提供了錯誤的用戶名和密碼,我的應用程序將運行到身份驗證錯誤:
Caused by: org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.amqp.rabbit.config.internalRabbitListenerEndpointRegistry'; nested exception is org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
Caused by: org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
Caused by: org.springframework.amqp.rabbit.listener.exception.FatalListenerStartupException: Authentication failure
Caused by: org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
在同一時間,我的應用程序中與RabbitMQ無關的其他部分將無法運行。
是否有一種方法可以將RabbitMQ bean錯誤僅包含在本身中,而不包含所有其他組件,以便應用程序的其餘部分可以運行?
您可以嘗試劃分您的上下文,以便rabbitMQ上下文將處於自己的上下文中。雖然 –
我不確定執行情況這是偶然的環境問題嗎?您是否可能沒有在特定環境中設置RabbitMQ,並且您仍希望應用程序能夠運行?我假設在生產中,你總是希望它存在,如果不是它會失敗? – Ben