35
35
import org .springframework .context .annotation .Bean ;
36
36
import org .springframework .context .annotation .Configuration ;
37
37
import org .springframework .http .client .ClientHttpRequestInterceptor ;
38
+ import org .springframework .util .CollectionUtils ;
38
39
39
40
/**
40
41
* Auto-configuration Ribbon for Polaris.
@@ -55,23 +56,38 @@ public PolarisLoadBalancerProperties polarisLoadBalancerProperties() {
55
56
}
56
57
57
58
@ Bean
58
- public RestTemplateCustomizer restTemplateCustomizer (
59
+ public RestTemplateCustomizer polarisRestTemplateCustomizer (
59
60
@ Autowired (required = false ) RetryLoadBalancerInterceptor retryLoadBalancerInterceptor ,
60
61
@ Autowired (required = false ) LoadBalancerInterceptor loadBalancerInterceptor ) {
61
62
return restTemplate -> {
62
63
List <ClientHttpRequestInterceptor > list = new ArrayList <>(restTemplate .getInterceptors ());
63
64
// LoadBalancerInterceptor must invoke before EnhancedRestTemplateInterceptor
64
- if (retryLoadBalancerInterceptor != null || loadBalancerInterceptor != null ) {
65
- int addIndex = list .size ();
65
+ int addIndex = list .size ();
66
+ if (CollectionUtils .containsInstance (list , retryLoadBalancerInterceptor ) || CollectionUtils .containsInstance (list , loadBalancerInterceptor )) {
67
+ ClientHttpRequestInterceptor enhancedRestTemplateInterceptor = null ;
66
68
for (int i = 0 ; i < list .size (); i ++) {
67
69
if (list .get (i ) instanceof EnhancedRestTemplateInterceptor ) {
70
+ enhancedRestTemplateInterceptor = list .get (i );
68
71
addIndex = i ;
69
72
}
70
73
}
71
- list .add (addIndex ,
72
- retryLoadBalancerInterceptor != null
73
- ? retryLoadBalancerInterceptor
74
- : loadBalancerInterceptor );
74
+ if (enhancedRestTemplateInterceptor != null ) {
75
+ list .remove (addIndex );
76
+ list .add (enhancedRestTemplateInterceptor );
77
+ }
78
+ }
79
+ else {
80
+ if (retryLoadBalancerInterceptor != null || loadBalancerInterceptor != null ) {
81
+ for (int i = 0 ; i < list .size (); i ++) {
82
+ if (list .get (i ) instanceof EnhancedRestTemplateInterceptor ) {
83
+ addIndex = i ;
84
+ }
85
+ }
86
+ list .add (addIndex ,
87
+ retryLoadBalancerInterceptor != null
88
+ ? retryLoadBalancerInterceptor
89
+ : loadBalancerInterceptor );
90
+ }
75
91
}
76
92
restTemplate .setInterceptors (list );
77
93
};
0 commit comments