Ribbon负载均衡的使用
前言
,如果为同一个的提供者在Eureka中注册了多个服务,那么客户端该如何选择服务呢?这时,就需要在客户端实现服务的负载均衡。在Spring Cloud中推荐使用Ribbon来实现负载均衡。
一、Ribbon简介
二、架构
三、开始使用Ribbon
1、为microservice order增加ribbon依赖,其实,该依赖是可以省略的,因为spring-cloud-starter-netflix-eureka-client中已经包含了spring-cloud-starter-netflix-ribbon:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
2、为RestTemplate设置@LoadBalanced注解
package com.oy.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
public class ServiceOrderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceOrderApplication.class, args);
}
@Bean
@LoadBalanced //负载均衡 ribbon
public RestTemplate restTemplate() {
return new RestTemplate();//httpClient
}
}
这样,RestTemplate就具备了负载均衡的功能。
3、改造orderService的实现
public Order createOrder() {
//1.创建订单对象
Order order = new Order();
order.setOid(100010);
order.setUid(3309);
//2.调用商品服务--查询所有商品的信息----
//Product[] productArray = restTemplate.getForObject("http://127.0.0.1:8081/product", Product[].class);
Product[] productArray = restTemplate.getForObject("http://service-product/product", Product[].class);//service-product是注册到注册中心的服务名
order.setProductList(Arrays.asList(productArray));
//2.返回
return order;
}
这种方式关键在于获取RestTemplat对象时要加上@LoadBalanced注解 ,否则restTemplate.getForObject方法会报java.net.UnknownHostException: service-order,而前面一种方式是手动指定了获取的服务实例,不需要加此注解。
4、重启订单服务进行测试
四、内部原理(可以启动多个product实例看效果,比如端口分别设为8082,8083,在下面2个类里打断点):
org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor
org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient
在执行请求前会经过org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor这个拦截器,并且在org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient中,通过serverId查找服务地址,通过一定的负载均衡策略去做真正的请求。
五、设置负载均衡策略
只需要在配置文件中添加配置
serviceId.ribbon.NFLoadBalancerRuleClassName=自定义的负载均衡策略类
例如在order微服务的yml配置文件中添加:
service-product:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
六、其它策略
接口:com.netflix.loadbalancer.IRule,其实现类:
策略描述: