什么是Ribbon?
目前主流的负载均衡分为两种:
- 集中式负载均衡 在消费者和服务提供方中间使用独立的代理方式进行负载,比如硬件有F5,软件如nginx
- 客户端根据自己的请求情况做负载均衡,Ribbon 就属于客户端自己做负载均衡
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端的负载均衡工具,Ribbon客户端组件提供一系列的完善的配置,比如超时、重试等
通过Load Balancer获取到服务提供的所有机器实例,Ribbon会自动基于某种规则(轮询、随机)去调用这些服务.
Ribbon也可以实现我们自己的负载均衡算法
客户端的负载均衡
例如Spring Cloud中的Ribbon,客户端会有一个服务器地址列表,在发送请求前通过负载均衡算法选择一个服务器,然后进行访问,这是客户端负载均衡,也就是在客户端就进行负载均衡算法的分配
详细链接: www.processon.com/view/link/6…
服务端的负载均衡
例如Nginx,通过Nginx进行负载均衡,先发送请求,然后通过负载均衡算法,在多个服务器之间选择一个进行访问.
即在服务器端再进行负载均衡算法分配
详细链接: www.processon.com/view/link/6…
常见的负载均衡算法
- 随机 通过随机选择服务进行执行,一般这种方式使用较少
- 轮训 负载均衡默认实现方式,请求来之后排队处理
- 加权轮训 通过对服务器性能的分型,给高配置,低负载的服务器分配更高的权重,均衡各个服务器的压力
- 地址Hash 通过客户端请求的地址的hash值取模映射进行服务器调度.ip hash
- 最小连接数 即使请求均衡了,压力不一定会均衡,最小连接数法就是根据服务器的情况,比如请求积压数等参数,将请求分配到当前压力最小的服务器上.最小活跃数
Ribbon的使用
1 |
public class RibbonDemo { public static void main(String[] args) { // 服务列表 List<Server> serverList = Lists.newArrayList( new Server("localhost", 8020), new Server("localhost", 8021)); // 构建负载实例 ILoadBalancer loadBalancer = LoadBalancerBuilder.newBuilder() .buildFixedServerListLoadBalancer(serverList); // 调用 5 次来测试效果 for (int i = 0; i < 5; i++) { String result = LoadBalancerCommand.<String>builder() .withLoadBalancer(loadBalancer).build() .submit(new ServerOperation<String>() { @Override public Observable<String> call(Server server) { String addr = "http://" + server.getHost() + ":" + server.getPort() + "/order/findOrderByUserId/1"; System.out.println(" 调用地址:" + addr); URL url = null; try { url = new URL(addr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); InputStream in = conn.getInputStream(); byte[] data = new byte[in.available()]; in.read(data); return Observable.just(new String(data)); } catch (Exception e) { e.printStackTrace(); } return null; } }).toBlocking().first(); System.out.println(" 调用结果:" + result); } } } 复制代码 |
Spring Cloud整合Ribbon
引入依赖
1 |
<!--添加ribbon的依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> 复制代码 |
nacos-discovery依赖了ribbon,可以不用再引入ribbon依赖
添加@LoadBalanced注解
1 |
@Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } 复制代码 |
Ribbon内部原理
详细链接: www.processon.com/view/link/6…
模拟Ribbon轮询算法实现
1 |
@Autowired private DiscoveryClient discoveryClient; public String getUri(String serviceName) { List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName); if (serviceInstances == null || serviceInstances.isEmpty()) { return null; } int serviceSize = serviceInstances.size(); // 轮询 int indexServer = incrementAndGetModulo(serviceSize); return serviceInstances.get(indexServer).getUri().toString(); } private AtomicInteger nextIndex = new AtomicInteger(0); private int incrementAndGetModulo(int modulo) { for (;;) { int current = nextIndex.get(); int next = (current + 1) % modulo; if (nextIndex.compareAndSet(current, next) && current < modulo){ return current; } } } 复制代码 |
@LoadBalanced 注解原理
LoadBalancerAutoConfiguration
@LoadBalanced利用@Qualifier作为restTemplates注入的筛选条件,筛选出具有负载均衡标识的RestTemplate
1 |
@Configuration( proxyBeanMethods = false ) @ConditionalOnClass({RestTemplate.class}) @ConditionalOnBean({LoadBalancerClient.class}) @EnableConfigurationProperties({LoadBalancerRetryProperties.class}) public class LoadBalancerAutoConfiguration { .... @Configuration( proxyBeanMethods = false ) @ConditionalOnMissingClass({"org.springframework.retry.support.RetryTemplate"}) static class LoadBalancerInterceptorConfig { LoadBalancerInterceptorConfig() { } @Bean public LoadBalancerInterceptor ribbonInterceptor(LoadBalancerClient loadBalancerClient, LoadBalancerRequestFactory requestFactory) { return new LoadBalancerInterceptor(loadBalancerClient, requestFactory); } @Bean @ConditionalOnMissingBean public RestTemplateCustomizer restTemplateCustomizer(final LoadBalancerInterceptor loadBalancerInterceptor) { return (restTemplate) -> { List<ClientHttpRequestInterceptor> list = new ArrayList(restTemplate.getInterceptors()); // 添加了loadBancerInterceptor拦截器 list.add(loadBalancerInterceptor); restTemplate.setInterceptors(list); }; } } } 复制代码 |
Ribbon相关接口
org.springframework.cloud.netflix.ribbon.****RibbonClientConfiguration
IClientConfig:Ribbon的客户端配置,默认采用DefaultClientConfigImpl实现
IRule:Ribbon的负载均衡策略,默认采用ZoneAvoidanceRule实现,该策略能够在多区域环境下选出最佳区域的实例进行访问
IPing:Ribbon的实例检查策略,默认采用DummyPing实现,该检查策略是一个特殊的实现,实际上它并不会检查实例是否可用,而是始终返回true,默认认为所有服务实例都是可用的
ServerList:服务实例清单的维护机制,默认采用ConfigurationBasedServerList实现
ServerListFilter:服务实例清单过滤机制,默认采ZonePreferenceServerListFilter,该策略能够优先过滤出与请求方处于同区域的服务实例
ILoadBalancer:负载均衡器,默认采用ZoneAwareLoadBalancer实现,它具备了区域感知的能力
Ribbon负载均衡策略
- RandomRule: 随机选择一个Server
- RetryRule: 对选定的负载均衡策略机上重试机制,在一个配置时间段内当选择Server不成功,则一直尝试使用subRule的方式选择一个可用的server
- RoundRobinRule: 轮询选择, 轮询index,选择index对应位置的Server
- AvailabilityFilteringRule: 过滤掉一直连接失败的被标记为circuit tripped的后端Server,并过滤掉那些高并发的后端Server或者使用一个AvailabilityPredicate来包含过滤server的逻辑,其实就是检查status里记录的各个Server的运行状态。
- BestAvailableRule: 选择一个最小的并发请求的Server,逐个考察Server,如果Server被tripped了,则跳过
- WeightedResponseTimeRule: 根据响应时间加权,响应时间越长,权重越小,被选中的可能性越低
- ZoneAvoidanceRule: 默认的负载均衡策略,即复合判断Server所在区域的性能和Server的可用性选择Server,在没有区域的环境下,类似于轮询(RandomRule)
- NacosRule: 同集群优先调用
修改默认负载均衡策略
- 全局配置:调用其他微服务,一律使用指定的负载均衡算法
- @Bean public IRule() { // 指定使用Nacos提供的负载均衡策略(优先调用同一集群的实例,基于随机权重) return new NacosRule(); } 复制代码
- 局部配置:调用指定微服务提供的服务时,使用对应的负载均衡算法
- 修改application.yml
- # 被调用的微服务名 mall-order: ribbon: # 指定使用Nacos提供的负载均衡策略(优先调用同一集群的实例,基于随机&权重) NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule 复制代码
自定义负载均衡策略
通过实现IRule接口可以自定义负载策略,主要的选择服务逻辑在 choose 方法中
实现基于Nacos权重的负载均衡策略
1 |
@Slf4j public class NacosRandomWithWeightRule extends AbstractLoadBalancerRule { @Autowired private NacosDiscoveryProperties nacosDiscoveryProperties; @Override public Server choose(Object key) { DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer(); String serviceName = loadBalancer.getName(); NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); try { //nacos基于权重的算法 Instance instance = namingService.selectOneHealthyInstance(serviceName); log.info(instance.getIp() + ":" + instance.getPort()); return new NacosServer(instance); } catch (NacosException e) { log.error("获取服务实例异常:{}", e.getMessage()); e.printStackTrace(); } return null; } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } } 复制代码 |
配置自定义的策略
- 局部配置
- 修改application.yml
1 |
# 被调用的微服务名 mall-order: ribbon: # 自定义的负载均衡策略(基于随机&权重) NFLoadBalancerRuleClassName: com.tuling.mall.ribbondemo.rule.NacosRandomWithWeightRule 复制代码 |
- 全局配置
- @Bean public IRule ribbonRule() { return new NacosRandomWithWeightRule(); } 复制代码
- 局部配置第二种方式
可以利用@RibbonClient指定微服务及其负载均衡策略
1 |
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DruidDataSourceAutoConfigure.class}) //@RibbonClient(name = "mall-order",configuration = RibbonConfig.class) //配置多个 RibbonConfig不能被@SpringbootApplication的@CompentScan扫描到,否则就是全局配置的效果 @RibbonClients(value = { // 在SpringBoot主程序扫描的包外定义配置类 @RibbonClient(name = "mall-order",configuration = RibbonConfig.class), @RibbonClient(name = "mall-account",configuration = RibbonConfig.class) }) 复制代码 |
注意: 不能写在@SpringbootApplication注解的@CompentScan扫描得到的地方,否则自定义的配置类就会被所有的 RibbonClients共享.不建议这么使用,推荐yml方式
饥饿加载
在进行服务调用的时候,如果网络情况不好,第一次调用会超时
Ribbon默认懒加载,意味着只有在发起调用的时候才会创建客户端
开启饥饿加载,解决第一次调用慢的问题
1 |
ribbon: eager-load: # 开启ribbon饥饿加载 enabled: true # 配置mall-order使用ribbon饥饿加载,多个使用逗号分隔 clients: mall-order 复制代码 |
RibbonEagerLoadProperties
1 |
@ConfigurationProperties( prefix = "ribbon.eager-load" ) public class RibbonEagerLoadProperties { private boolean enabled = false; private List<String> clients; public RibbonEagerLoadProperties() { } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<String> getClients() { return this.clients; } public void setClients(List<String> clients) { this.clients = clients; } } |
原文链接:https://juejin.cn/post/7091532202936107016