加入ribbon依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
在启动器中加入:
@SpringBootApplication
@EnableEurekaClient
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
- 在
RestTemplate
中我们增加了一个@LoadBalanced
注解,该注解就是能够让RestTemplate
启用客户端负载均衡。
启动eureka服务器,启动多个service
访问资源,输出端口号,会发现端口号交替出现,则测试成功
直接使用Ribbon的API
另外,除了使用@LoadBalanced
注解外,我们还可以直接使用Ribbon所提供的LoadBalancerClient
来实现负载均衡:
@RestController
public class HelloController {
protected Logger logger = LoggerFactory.getLogger(HelloController.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return restTemplate.getForEntity("http://SERVICE-HELLO/hello", String.class).getBody();
}
@RequestMapping(value = "/helloEx", method = RequestMethod.GET)
public String helloEx() {
ServiceInstance instance = this.loadBalancerClient.choose("SERVICE-HELLO");
URI helloUri = URI.create(String.format("http://%s:%s/hello", instance.getHost(), instance.getPort()));
logger.info("Target service uri = {}. ", helloUri.toString());
return new RestTemplate().getForEntity(helloUri, String.class).getBody();
}
}