java1234开源博客系统
博客信息

Ribbon负载均衡

0
发布时间:『 2018-09-20 23:18』  博客类别:SpringCloud  阅读(5006) 评论(0)

Ribbon负载均衡


前面搭建了初步例子,但是还没实现真正负载均衡,我们这里要先搞三个服务提供者集群,然后才能演示负载均衡,以及负载均衡策略;


新建项目microservice-student-provider-1002,microservice-student-provider-1003

pom.xml,application.yml,以及java类都复制一份,启动类名称对应的改下;

yml配置文件有两处要对应的改下,port端口改下,以及服务实例名称改下;

QQ鎴浘20180920230402.jpg


为了方便查看具体执行了哪个服务提供者,我们再Controller控制器的方法里搞个打印语句;


QQ鎴浘20180920230639.jpg



配置完后,我们先来测试下,先启动三个eureka集群,再启动三个服务提供者集群;


先测试服务提供者:

http://localhost:1001/student/list

http://localhost:1002/student/list

http://localhost:1003/student/list


看看是否有结果;


再测试下 eureka:

http://eureka2001.java1234.com:2001/

http://eureka2002.java1234.com:2002/

http://eureka2003.java1234.com:2003/


QQ鎴浘20180920231116.jpg


有这种的话,就说明没问题;


然后再启动服务消费者:

http://localhost/student/list  多刷新几次 看控制台,我们看到 有默认的轮询策略,访问对应的服务提供者;


但是这种默认的轮询策略肯定是不能满足实际需求的,比如有3个服务提供者,突然挂了一个,这样的话,默认轮询 ,总有1/3的概率访问失败; 所以我们看下ribbon默认给我们提供的策略有哪些;

策略名策略声明策略描述实现说明
BestAvailableRulepublic class BestAvailableRule extends ClientConfigEnabledRoundRobinRule选择一个最小的并发请求的server逐个考察Server,如果Server被tripped了,则忽略,在选择其中ActiveRequestsCount最小的server
AvailabilityFilteringRulepublic class AvailabilityFilteringRule extends PredicateBasedRule过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值)使用一个AvailabilityPredicate来包含过滤server的逻辑,其实就就是检查status里记录的各个server的运行状态
WeightedResponseTimeRulepublic class WeightedResponseTimeRule extends RoundRobinRule根据响应时间分配一个weight,响应时间越长,weight越小,被选中的可能性越低。一个后台线程定期的从status里面读取评价响应时间,为每个server计算一个weight。Weight的计算也比较简单responsetime 减去每个server自己平均的responsetime是server的权重。当刚开始运行,没有形成status时,使用roubine策略选择server。
RetryRulepublic class RetryRule extends AbstractLoadBalancerRule对选定的负载均衡策略机上重试机制。在一个配置时间段内当选择server不成功,则一直尝试使用subRule的方式选择一个可用的server
RoundRobinRulepublic class RoundRobinRule extends AbstractLoadBalancerRuleroundRobin方式轮询选择server轮询index,选择index对应位置的server
RandomRulepublic class RandomRule extends AbstractLoadBalancerRule随机选择一个server在index上随机,选择index对应位置的server
ZoneAvoidanceRulepublic class ZoneAvoidanceRule extends PredicateBasedRule复合判断server所在区域的性能和server的可用性选择server使用ZoneAvoidancePredicate和AvailabilityPredicate来判断是否选择某个server,前一个判断判定一个zone的运行性能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用于过滤掉连接数过多的Server。

默认7个策略,根据具体产品需求,我们选用;


代码中如何假如呢;


服务消费端 SpringCloudConfig配置类  

指定IRule实现;


/**
	 * 自定义轮询算法
	 * @return
	 */
	@Bean
	public IRule myRule(){
		return new RetryRule();
	}

这里我们演示用 RetryRule,大伙可以自行测试;


用法很简单;


关键字:   Ribbon     负载均衡  
关注Java1234微信公众号
博主信息
Java1234_小锋
(知识改变命运,技术改变世界)
Powered by Java1234 V3.0 Copyright © 2012-2016 Java知识分享网 版权所有