本篇文章将介绍如何使用 Ribbon 完成发现服务的调用以及其负载均衡的规则的使用。 Spring Cloud Ribbon 是基于 Netflix Ribbon 实现的一套客户端负载均衡工具,其主要功能是提供客户端的软件负载均衡算法,将 Netflix 的中间层服务连接在一起。
其运行原理如下图:
Ribbon 运行时分成 2 个步骤: 1、先选择在同一个区域负载较少的 EurekaServer; 2、 再根据用户指定的策略,在从 EurekaServer 中获取注册列表中的服务信息进行调用。
添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
其实,添加 Eureka 包时,会自动添加 Ribbon 依赖包。 修改请求类:
@Configuration
public class RestConfiguration {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
正如上文介绍的,Ribbon 是客户端负载均衡工具,所以在 getRestTemplate 方法上添加 @LoadBalanced 注解实现负载均衡。
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private RestTemplate restTemplate;
// @RequestMapping("get/{id}")
// public User get(@PathVariable("id") Integer id) throws Exception {
// // 没有使用 Eureka 时,uri 为消息提供者的地址,需要指定 ip 和 端口
// return restTemplate.getForObject(new URI("http://localhost:8081/provider/user/get/" + id), User.class);
// }
// @Autowired
// private DiscoveryClient client;
//
// @RequestMapping("get/{id}")
// public User get(@PathVariable("id") Integer id) throws Exception {
//
// List<ServiceInstance> list = this.client.getInstances("USER-API");
// String uri = "";
// for (ServiceInstance instance : list) {
// if (instance.getUri() != null && !"".equals(instance.getUri().toString())) {
// uri = instance.getUri().toString();
// break;
// }
// }
// return restTemplate.getForObject(uri + "/provider/user/get/" + id, User.class);
// }
@RequestMapping("get/{id}")
public User get(@PathVariable("id") Integer id) throws Exception {
// 使用 Eureka + Ribbon 后,uri 填写服务名称即可
return restTemplate.getForObject("http://USER-API/provider/user/get/" + id, User.class);
}
}
修改 DiscoveryClient 相关代码,使用 USER-API 服务名称作为请求 URL。
在启动类上将 @EnableDiscoveryClient 替换成 @EnableEurekaClient 注解。 完成上边 4 个操作后,启动 user-consumer 项目使用浏览器访问接口,运行结果如下:
由图可知,Ribbon 默认使用负载均衡的策略是轮询,对服务进行调用。 源码下载