风止雨歇

自定义Ribbon的负载均衡策略

自定义负载均衡策略

官方文档指出:自定义的负载均衡配置类不能放在 @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<Server> upList = lb.getReachableServers(); //当前存活的服务
            List<Server> 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、配置类中增加自定义规则

@Configuration
public 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

posted on 2019-05-30 23:24  风止雨歇  阅读(3470)  评论(1编辑  收藏  举报

导航