在工程的启动类中,注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。代码如下:
@SpringBootApplication
public class EurekaConsumerRibbonApplication {
@Autowired
private RestTemplateBuilder restTemplateBuilder;
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerRibbonApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return restTemplateBuilder.build();
}
}
但是!但是!但是!通过RestTemplateBuilder.build()生成的RestTemplate负载均衡是无效的!会一直访问ribbonServerList中的第一个服务,如果第一个服务挂掉,则会出现访问失败,直到eureka将这个挂掉的服务清理,并且客户端刷新从注册中心拉取的缓存信息,此时才会恢复服务,但是仍然只会访问第一个服务,负载均衡仍然失效。
怎么样使用负载均衡才会正常生效呢?不能使用RestTemplateBuilder,而要直接return new RestTemplate();代码如下:
@SpringBootApplication
public class EurekaConsumerRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerRibbonApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}