Ribbon自定义修改负载均衡

Ribbon

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具,主要功能是提供客户端的软件负载均衡算法和服务调用。
如果使用的RestTemplate进行服务调用,那么创建RestTemplate的方法上面加@LoadBalanced注解就会开启Ribbon的负载均衡,Ribbon负载均衡有以下7中规则,默认轮询
Ribbon自定义修改负载均衡_第1张图片
修改负载均衡规则为随机
1.建立自定义配置类,自定义配置类不能放在@ComponentScan当前包和和子包下,否则会被所有Ribbon客户端所共享

@Configuration
public class MyRuleConfig {
    @Bean
    public IRule rule(){
    //随机
        return new RandomRule();
    }
}

2.启动类上根据自己需求添加全局注解或者局部注解RibbonClients

//针对全局修改
@RibbonClients(defaultConfiguration = MyRuleConfig.class)
//针对某个服务修改
@RibbonClient(name = "cloud-payment-service",configuration = MyRuleConfig.class)

3.结合OpenFeign写一个自定义的负载均衡规则
1.实现一个OpenFeign跨进程调用服务的例子(https://blog.csdn.net/weixin_44728473/article/details/126043232?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22126043232%22%2C%22source%22%3A%22weixin_44728473%22%7D&ctrtid=pfPyf)
2.自定义一个类继承AbstractLoadBalancerRule 接口 模拟的业务逻辑,对i取模,为零的返回权重小的服务 的ip地址和端口号,不为零返回权重大的服务

public class MyRule extends AbstractLoadBalancerRule {

    //Nacos自带的自定义配置
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    //AtomicInteger线程安全
    public static AtomicInteger count = new AtomicInteger(0);

    Server server = null;

    @SneakyThrows
    @Override
    public Server choose(Object key) {

        //BaseLoadBalancer为bstractLoadBalancerRule 基类
        BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
        //获取到服务名
        String name = loadBalancer.getName();

        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

        List<Instance> instances = namingService.selectInstances(name, true);

       /*
       * 模拟的业务逻辑
       * 对i取模,为零的返回权重小的服务 的ip地址和端口号
       * 不为零返回权重大的服务
       * */
        /*获取服务最大权重*/
        Instance instanceMax = instances.stream().max(Comparator.comparing(Instance::getWeight)).get();
        /*获取服务最小权重*/
        Instance instanceMin = instances.stream().min(Comparator.comparing(Instance::getWeight)).get();
        /*相当于i++*/
        int i = count.getAndAdd(1);
        int mod = i % 5;
        if (mod == 0) {
            server = new Server(instanceMin.getIp(), instanceMin.getPort());
        } else {
            server = new Server(instanceMax.getIp(), instanceMax.getPort());
        }
        return server;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

}

2.自定义配置类(RibbonClient可以加在任何地方)

@Configuration
//针对全局修改
//@RibbonClients(defaultConfiguration = MyRuleConfig.class)
//针对某个服务修改
@RibbonClient(name = "nacos-app-a", configuration = MyRuleConfig.class)
public class MyRuleConfig {
    @Bean
    public IRule rule() {
      //返回上面自定义的规则类
        return new MyRule();
    }
}

你可能感兴趣的:(SpringCloud,负载均衡,ribbon,java)