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