博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自定义Ribbon的负载均衡策略
阅读量:4605 次
发布时间:2019-06-09

本文共 2733 字,大约阅读时间需要 9 分钟。

自定义负载均衡策略

官方文档指出:自定义的负载均衡配置类不能放在 @componentScan 所扫描的当前包下及其子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,也就是说我们达不到特殊化定制的目的了;

 

要求自定义的算法:依旧是轮询策略,但是每个服务器被调用5次后轮到下一个服务,即以前是每个服务被调用1次,现在是每个被调用5次。

 

打开消费者工程:

1、自定义算法类必须继承 AbstractLoadBalanceRule

启动类在com.yufeng.springcloud 包下,所以我们新建一个包: con.yufeng.myrule,并在该包下新建一个类:CustomeRule 

public class CustomeRule extends AbstractLoadBalancerRule{     /*     total = 0 // 当total==5以后,我们指针才能往下走,     index = 0 // 当前对外提供服务的服务器地址,     total需要重新置为零,但是已经达到过一个5次,我们的index = 1     */    private int total = 0;             // 总共被调用的次数,目前要求每台被调用5次    private int currentIndex = 0;    // 当前提供服务的机器号    public Server choose(ILoadBalancer lb, Object key) {        if (lb == null) {            return null;        }        Server server = null;        while (server == null) {            if (Thread.interrupted()) {                return null;            }            List
upList = lb.getReachableServers(); //当前存活的服务 List
allList = lb.getAllServers(); //获取全部的服务 int serverCount = allList.size(); if (serverCount == 0) { return null; } //int index = rand.nextInt(serverCount); //server = upList.get(index); if(total < 5) { server = upList.get(currentIndex); total++; }else { total = 0; currentIndex++; if(currentIndex >= upList.size()) { currentIndex = 0; } } if (server == null) { Thread.yield(); continue; } if (server.isAlive()) { return (server); } // Shouldn't actually happen.. but must be transient or a bug. server = null; Thread.yield(); } return server; } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { }}

 2、配置类中增加自定义规则

@Configurationpublic class ConfigBean{    @Bean    @LoadBalanced //Ribbon 是客户端负载均衡的工具;    public RestTemplate getRestTemplate()    {        return new RestTemplate();    }    @Bean    public IRule myRule()    {        return new CustomeRule(); //自定义负载均衡规则    }}

3、主启动类添加 @RibbonClient 注解,name和configuration参数很重要;

在启动该微服务的时候就能去加载我们自定义的Ribbon配置类,从而使配置生效:

  @RibbonClient(name="microservicecloud-dept", configuration=ConfigBean.class)

  name指定针对哪个服务 进行负载均衡,而configuration指定负载均衡的算法具体实现类。

4、启动该消费者服务,然后访问:http://localhost/consumer/dept/get/1,可以看到先访问生产者1服务5次,然后访问生产者2服务5次......

 

 

 

ConfigBean

转载于:https://www.cnblogs.com/yufeng218/p/10952724.html

你可能感兴趣的文章
HDU5950【矩阵快速幂】
查看>>
在线C++编译器
查看>>
C#中各种serialization的比较
查看>>
P2617 Dynamic Rankings
查看>>
工作学习常识1
查看>>
github开发
查看>>
Emacs学习笔记(13):在Emacs中打开pdf
查看>>
flask模板应用-空白控制 --
查看>>
清理SharePoint 2013 安装配置环境
查看>>
学习过程笔记 7月上
查看>>
ASP.NET WebAPI String 传值问题
查看>>
【2017-3-1】冒泡排序
查看>>
[转载]后缀数组算法总结
查看>>
pandas数据结构练习题(部分)
查看>>
NOI2016 区间 【线段树】
查看>>
第二阶段团队绩效评估
查看>>
.net第三方数据库物理卡号同步功能实现
查看>>
机器学习02_逻辑回归作业(附加)
查看>>
zstu.4189: 逻辑运算(构建 && 前缀表达式入门)
查看>>
iOS中常见的自定义宏
查看>>