扩展Ribbon,支持Naocs权重

扩展Ribbon,支持Naocs权重

÷编写代码

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        //读取配置文件,并且初始化
    }

    @Override
    public Server choose(Object o) {
        try {
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            //获得服务名
            String name = loadBalancer.getName();
            //拿到服务相关的api
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            //nacos client自动通过基于权重的负载均衡算法,给我们选择一个实例
            Instance instant = namingService.selectOneHealthyInstance(name);
            log.info("选择的实例是:prot={},instant={}", instant.getPort(), instant);
            return new NacosServer(instant);
        } catch (NacosException e) {
            e.printStackTrace();
            return null;
        }

    }
}

修改配置类

@Configuration
public class RibbonConfiguration {
    @Bean
    public IRule ribbonRule() {
        return new NacosWeightedRule();
    }
}

在配置文件中使用

spring-cloud-alibaba-nacos:
  ribbon:
    NFLoadBalancerRuleClassName: com.yz.alibaba.config.NacosWeightedRule

修改nacos权重