16
16
17
17
package org .springframework .cloud .loadbalancer .support ;
18
18
19
- import java . util . List ;
20
-
19
+ import org . apache . commons . logging . Log ;
20
+ import org . apache . commons . logging . LogFactory ;
21
21
import org .springframework .boot .context .event .ApplicationReadyEvent ;
22
+ import org .springframework .cloud .client .ServiceInstance ;
23
+ import org .springframework .cloud .client .loadbalancer .Response ;
24
+ import org .springframework .cloud .client .loadbalancer .reactive .ReactiveLoadBalancer ;
22
25
import org .springframework .context .ApplicationListener ;
26
+ import reactor .core .publisher .Mono ;
27
+
28
+ import java .util .List ;
23
29
24
30
/**
25
- * @author Andrii Bohutskyi
31
+ * @author Andrii Bohutskyi, Haotian Zhang
26
32
*/
27
33
public class LoadBalancerEagerContextInitializer implements ApplicationListener <ApplicationReadyEvent > {
28
34
35
+ private static final Log log = LogFactory .getLog (LoadBalancerEagerContextInitializer .class );
36
+
29
37
private final LoadBalancerClientFactory factory ;
30
38
31
39
private final List <String > serviceNames ;
@@ -37,7 +45,17 @@ public LoadBalancerEagerContextInitializer(LoadBalancerClientFactory factory, Li
37
45
38
46
@ Override
39
47
public void onApplicationEvent (ApplicationReadyEvent applicationReadyEvent ) {
40
- serviceNames .forEach (factory ::getInstance );
48
+ serviceNames .forEach (serviceName -> {
49
+ ReactiveLoadBalancer <ServiceInstance > loadBalancer = factory .getInstance (serviceName );
50
+ if (loadBalancer != null ) {
51
+ Response <ServiceInstance > loadBalancerResponse = Mono .from (loadBalancer .choose ()).block ();
52
+ if (log .isDebugEnabled () && loadBalancerResponse != null ) {
53
+ log .debug ("LoadBalancer for service: " + serviceName + " initialized with chosen instance: "
54
+ + loadBalancerResponse .getServer ().getHost () + ":" + loadBalancerResponse .getServer ().getPort ());
55
+ }
56
+ log .info ("LoadBalancer for service: " + serviceName + " initialized" );
57
+ }
58
+ });
41
59
}
42
60
43
61
}
0 commit comments