Ribbon - 負載均衡流程中提到,serviceId對應的AnnotationConfigApplicationContext在第一次調用的時候才建立(因此叫懶加載),那有可能形成調用的超時,那有沒有辦法提早加載呢?
在RibbonAutoConfiguration類中,有個RibbonApplicationContextInitializer,若是不須要懶加載,咱們就須要ribbon.eager-load.enabled的值爲true。spring
@Bean @ConditionalOnProperty("ribbon.eager-load.enabled") public RibbonApplicationContextInitializer ribbonApplicationContextInitializer() { return new RibbonApplicationContextInitializer(springClientFactory(), ribbonEagerLoadProperties.getClients()); }
RibbonApplicationContextInitializer是實現ApplicationListener<ApplicationReadyEvent>,因此當上下文準備好的時候,就會調用onApplicationEvent方法,而後繼續調用initialize方法,因此咱們並非說ribbon.eager-load.enabled的值設置true就能夠的,還須要設置clientNames。segmentfault
protected void initialize() { if (clientNames != null) { for (String clientName : clientNames) { this.springClientFactory.getContext(clientName); } } }
爲了去掉懶加載,個人配置以下,clients能夠是多個:負載均衡
ribbon: eager-load: enabled: true clients: eureka-provider