2017-08-07 21 views
0

現在我正在研究包含多個組件的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錯誤僅包含在本身中,而不包含所有其他組件,以便應用程序的其餘部分可以運行?

+0

您可以嘗試劃分您的上下文,以便rabbitMQ上下文將處於自己的上下文中。雖然 –

+0

我不確定執行情況這是偶然的環境問題嗎?您是否可能沒有在特定環境中設置RabbitMQ,並且您仍希望應用程序能夠運行?我假設在生產中,你總是希望它存在,如果不是它會失敗? – Ben

回答

1

認證錯誤被認爲是致命的。

對於短暫錯誤(例如代理未運行),應用程序將啓動並嘗試重新連接。

FatalListenerStartupException

你不顯示監聽器配置,但可以通過autoStartup屬性配置偵聽容器爲不自動啓動。如果爲false,上下文將始終加載正常。

然後您可以嘗試start()代碼中的容器並捕獲異常。

+0

感謝您的回覆。有沒有辦法讓偵聽器自動啓動,遇到認證錯誤時暫停,同時讓其他應用程序運行,並在提供正確憑據時恢復? – pike

+0

否;您需要自己管理容器生命週期以獲得所需的功能 - 在應用程序運行時動態更改憑證配置是非常不尋常的。 –

+0

聽起來不錯。感謝您的確認。 – pike

相關問題