Spring Cloud的commons模块提供了一个@LoadBalanced注解,方便我们对RestTemplate添加一个LoadBalancerClient,以实现客户端负载均衡。通过源码可以发现这是一个标记注解:
/**
* Annotation to mark a RestTemplate bean to be configured
* to use a LoadBalancerClient
* @author Spencer Gibb
*/
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Qualifier
public @interface LoadBalanced {
}
因为Spring Boot的自动配置机制,我们可以在这个包下看到一个LoadBalancerAutoConfiguration
自动配置类:
/**
* Auto configuration for Ribbon (client side load
* balancing).
*
* @author Spencer Gibb
* @author Dave Syer
* @author Will Tran
*/
@Configuration
@ConditionalOnClass(RestTemplate.class)
@ConditionalOnBean(LoadBalancerClient.class)
@EnableConfigurationProperties(LoadBalancerRetryProperties.class)
public class LoadBalancerAutoConfiguration {
@LoadBalanced
@Autowired(required = false)
private List<RestTemplate> restTemplates = Collections.emptyList();//这里持有@LoadBalanced标记的RestTemplate实例
@Bean
public SmartInitializingSingleton loadBalancedRestTemplateInitializer(
final List<RestTemplateCustomizer> customizers) {
return new SmartInitializingSingleton() {
//为restTemplate添加定制
@Override
public void afterSingletonsInstantiated() {
for (RestTemplate restTemplate :LoadBalancerAutoConfiguration.this.restTemplates) {
for (RestTemplateCustomizer customizer
: customizers) {
customizer.customize(restTemplate);
}
}
}
};
}
@Autowired(required = false)
private List<LoadBalancerRequestTransformer> transformers = Collections.emptyList();
@Bean
@ConditionalOnMissingBean
public LoadBalancerRequestFactory loadBalancerRequestFactory(
LoadBalancerClient