基于nacos扩展Ribbon同一集群优先调用

2021-03-12  本文已影响0人  G__yuan

还是同样老样子,自己编写负载均衡规则

public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {


    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    /**
     * 1:找到指定服务的所有实例 A
     * 2:过滤出相同集群下的实例 B
     * 3:如果B为空,则用A
     * 4:基于权重的负载均衡算法,返回一个实例
     */
    @Override
    public Server choose(Object o) {
        //拿到配置文件中的集群名称
        String clusterName = nacosDiscoveryProperties.getClusterName();
        BaseLoadBalancer loadBalancer = (BaseLoadBalancer)this.getLoadBalancer();
        String name = loadBalancer.getName();
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
        try {
            //拿到目标服务的所有实例
            List<Instance> allInstances = namingService.getAllInstances(name);
            List<Instance> sameClusterInstances = allInstances.stream().filter(instance ->
                    clusterName.equals(instance.getClusterName())
            ).collect(Collectors.toList());
            List<Instance> instancesToBeChose = new ArrayList<>();
            if (CollectionUtils.isEmpty(sameClusterInstances)){
                instancesToBeChose = allInstances;
            }else{
                instancesToBeChose = sameClusterInstances;
            }
            Instance hostByRandomWeight2 = ExtendBalancer.getHostByRandomWeight2(instancesToBeChose);
            return new NacosServer(hostByRandomWeight2);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }
}
/**
 * 该类是因为nacos中getHostByRandomWeight方法是protected修饰的无法访问,所以使用该办法奇技淫巧来访问nacos的getHostByRandomWeight方法
 */
class ExtendBalancer extends Balancer {
    public static Instance getHostByRandomWeight2(List<Instance> hosts){
        return getHostByRandomWeight(hosts);
    }
}

接下来和之前一样,将该规则指定使用即可。

上一篇下一篇

猜你喜欢

热点阅读