自定义负载均衡(Ribbon)

 增加自定义负载均衡实现类

package com.learning.springcloud.ribbon.rule;
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 CustomRule extends AbstractLoadBalancerRule {
    @Override    
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override    
    public Server choose(Object key) {
        ILoadBalancer loadBalancer = this.getLoadBalancer();        
        // 获取当前请求的服务的实例        
        List reachableServers = loadBalancer.getReachableServers();        
        int random = ThreadLocalRandom.current().nextInt(reachableServers.size());        
        Server  server = reachableServers.get(random);        
        return server;    
    }
}

 配置自定义负载均衡策略

  • 修改配置文件 application.yml
stock-service:
  ribbon:
    NFLoadBalancerRuleClassName:  com.learning.springcloud.ribbon.rule.CustomRule
    # NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule


 饥饿加载负载均衡策略

ribbon:
  eager-load:
    # 开启 ribbon 饥饿记载    
    enabled: true    
    # 配置 需要饥饿加载的服务名,多个逗号分割    
    clients: stock-service

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