springcloud-custom ribbon load balancing algorithm

In some cases, the built-in load balancing algorithm is not suitable for us, therefore, we need to customize our own load balancing algorithm

This article operates springcloud practice-ribbon based on the following article code to
achieve load balancing

1. Write configuration and algorithm

1. Create a new folder config in the same level directory as springcloud

Insert picture description here

2. Write a custom load balancing algorithm

This algorithm does not need to be written all by ourselves, we can copy the code it has already implemented, and then modify the key algorithm, as follows

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.hzxy.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;


public class YeRule extends AbstractLoadBalancerRule {
    
    
    public YeRule() {
    
    
    }

    //每个服务访问5次,换下一个服务(3个)

    //total=0,默认=0,如果=5,我们指向下一个服务结点
    //index=0,默认=0,如果total=5,index+1

    private int total = 0;     //被调用的次数
    private int currentIndex = 0;  //当前是谁在提供服务

    @SuppressWarnings({
    
    "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
    
    
        if (lb == null) {
    
    
            return null;
        } else {
    
    
            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 = this.chooseRandomInt(serverCount);       //生成区间随机数
//                server = (Server)upList.get(index);                  //从活着的服务中,随机获取一个
                //-------------------------------------------------------------

                if (total<5){
    
    
                    server = upList.get(currentIndex);
                    total++;
                }else {
    
    
                    total = 0;
                    currentIndex++;
                    if (currentIndex>=upList.size()){
    
    
                        currentIndex = 0;
                    }
                    server = upList.get(currentIndex); //从活着的服务中,获取指定的服务来进行操作
                }

                //-------------------------------------------------------------


                if (server == null) {
    
    
                    Thread.yield();
                } else {
    
    
                    if (server.isAlive()) {
    
    
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
    
    
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
    
    
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    
    
    }
}

3. Register your own implementation to the spring bean

code show as below:

package com.hzxy.config;

import com.netflix.loadbalancer.IRule;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class YbgRule {
    
    

    @Bean
    public IRule myRule(){
    
    
        return new YeRule();
    }
}

2. Modify the startup class

Add the @RibbonClient annotation, the first parameter is the service name, and the second parameter is the class file of the YbgRule of your configuration algorithm

package com.hzxy.springcloud;

import com.hzxy.config.YbgRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;


// ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心ip地址和端口号
@SpringBootApplication
@EnableEurekaClient  //自动配置
// 在微服务启动的时候就能去加载,我们自定义ribbon类
@RibbonClient(name = "springcloud-provider-user",configuration = YbgRule.class)
public class Consumer_80 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(Consumer_80.class,args);
    }
}

3. Test

Always visit, change a database every 5 times, the test is successful!
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43520670/article/details/114285190