前面说到基于nacos的注册发现有可以扩展实现我们自己的负载均衡算法(Nacos数据模型),来实现同集群调用,是基于spring.cloud.nacos.discovery.cluster-name参数。另外基于spring.cloud.nacos.discovery.metadata参数也可以实现金丝雀发布调用。这里就使用ribbon来实现这两种负载均衡算法。

直接使用feign调用,因为feign里面就是用的ribbon,引入feign依赖也就引入了ribbon

        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

1.继承com.netflix.loadbalancer.AbstractLoadBalancerRule 实现自己的负载均衡算法,从NacosDiscoveryProperties中获取实例信息,然后筛选出来cluster-name和metadata中version相同的实例,进行调用。

package com.nijunyang.order.ribbon.rule;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
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.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List; /**
* Description: 集群和版本规则
* Created by nijunyang on 2020/12/14 21:36
*/
@Slf4j
public class ClusterWithVersionRule extends AbstractLoadBalancerRule { @Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties; /**
* 重写choose方法
* @param key
* @return
*/
@SneakyThrows
@Override
public Server choose(Object key) {
//获取服务配置的集群名
String clusterName = nacosDiscoveryProperties.getClusterName();
//当前的版本号 配置文件配置的metadata信息
String currentVersion = nacosDiscoveryProperties.getMetadata().get("version");
//获取负载均衡器
BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) getLoadBalancer();
//调用服务的名字
String invokedServerName = baseLoadBalancer.getName();
//获取namingServer(包含nacos注册发现相关api)
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
//获取被调用的服务的所有实例
List<Instance> invokedAllInstanceList = namingService.getAllInstances(invokedServerName);
//同集群同版本
List<Instance> theSameClusterAndVersionList = new ArrayList<>();
//跨集群同版本
List<Instance> theSameVersionList = new ArrayList<>();
for (Instance instance : invokedAllInstanceList) {
if (clusterName.equalsIgnoreCase(instance.getClusterName())
&& currentVersion.equalsIgnoreCase(instance.getMetadata().get("version"))) {
theSameClusterAndVersionList.add(instance);
} else if (currentVersion.equalsIgnoreCase(instance.getMetadata().get("version"))) {
theSameVersionList.add(instance);
}
}
Instance invokedInstance;
if (theSameClusterAndVersionList.isEmpty()) {
//跨集群同版本调用, 随机选一个
if (theSameVersionList.isEmpty()) {
throw new RuntimeException("无对应版本服务");
}
SecureRandom random = new SecureRandom();
int i = random.nextInt(theSameVersionList.size());
invokedInstance = theSameVersionList.get(i);
} else {
//同集群同版本调用 随机选一个
SecureRandom random = new SecureRandom();
int i = random.nextInt(theSameClusterAndVersionList.size());
invokedInstance = theSameClusterAndVersionList.get(i);
}
return new NacosServer(invokedInstance);
} @Override
public void initWithNiwsConfig(IClientConfig iClientConfig) { }
}

2.配置自定义的负载均衡算法

spring:
application:
name: order
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #不用写协议
# namespace: 688bf906-8b48-4ee2-a433-828f042ec860 #test id
# group: pay
cluster-name: CD
metadata:
version: v2 ribbon:
NFLoadBalancerRuleClassName: com.nijunyang.order.ribbon.rule.ClusterWithVersionRule #指定全局的负载均衡算法
eager-load:
enabled: true #饥饿加载(ribbon客户端不是在服务启动的时候加载的,所以可能第一次调用会很慢,甚至超时)
clients: stock #指定哪些服务使用饥饿加载
#按服务指定负载均衡算法
stock:
ribbon:
NFLoadBalancerRuleClassName: com.nijunyang.order.ribbon.rule.ClusterWithVersionRule
eager-load:
enabled: true

当需要指定某一服务使用某一负载均衡算法的时候,不要让spring容器扫描到该规则。在配置文件中如上配置即可。

完整代码:https://github.com/bluedarkni/study/tree/master/cloud-alibaba

基于nacos注册中心的ribbon定制规则的更多相关文章

  1. Spring Cloud 系列之 Alibaba Nacos 注册中心(一)

    前言 从本章节开始,我们学习 Spring Cloud Alibaba 相关微服务组件. Spring Cloud Alibaba 介绍 Spring Cloud Alibaba 致力于提供微服务开发 ...

  2. 手动造轮子——为Ocelot集成Nacos注册中心

    前言     近期在看博客的时候或者在群里看聊天的时候,发现很多都提到了Ocelot网关的问题.我之前也研究过一点,网关本身是一种通用的解决方案,主要的工作就是拦截请求统一处理,比如认证.授权.熔断. ...

  3. Spring Cloud 系列之 Alibaba Nacos 注册中心(二)

    本篇文章为系列文章,未读第一集的同学请猛戳这里:Spring Cloud 系列之 Alibaba Nacos 注册中心(一) 本篇文章讲解 Nacos 注册中心集群环境搭建. Nacos 集群环境搭建 ...

  4. SpringCloud Alibaba实战(7:nacos注册中心管理微服务)

    源码地址:https://gitee.com/fighter3/eshop-project.git 持续更新中-- 在上一节我们已经完成了Nacos Server的本地部署,这一节我们学习如何将Nac ...

  5. Nacos注册中心之概要设计

    本文已收录 https://github.com/lkxiaolou/lkxiaolou 欢迎star. 前言 在之前的文章中分析了Nacos配置中心,配置中心的核心是配置的创建.读取.推送. 注册中 ...

  6. Nacos注册中心和配置中心流程原理

    一.Nacos注册中心 1.服务启动后---->服务注册原理 springCloud集成Nacos实现原理: 服务启动时,在spring-cloud-commons包下 spring.facto ...

  7. 5-2 Nacos注册中心

    Nacos注册中心 什么Nacos Nacos是Spring Cloud Alibaba提供的一个软件 这个软件主要具有注册中心和配置中心的功能 我们先学习它注册中心的功能 微服务中所有项目都必须注册 ...

  8. Spring Cloud Alibaba 使用nacos 注册中心

    ### 背景 上一文我们讲到了如何去搭建注册中心,这一次我们讲述如何使用nacos作为注册中心 ### spring-cloud-alibaba-basis 创建基础依赖 首先我们创建一个spring ...

  9. Spring Cloud Alibaba(4)---Nacos(注册中心)

    Nacos(注册中心) 有关Spring Cloud Alibaba之前写过三篇文章. Spring Cloud Alibaba(1)---入门篇 Spring Cloud Alibaba(2)--- ...

随机推荐

  1. JVM中的常量池详解

    在Java的内存分配中,总共3种常量池: 转发链接:https://blog.csdn.net/zm13007310400/article/details/77534349 1.字符串常量池(Stri ...

  2. Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理

    本文完整代码下载点击 一. 前言 相信了解过我或者看过我之前的系列文章应该多少知道点我写这些文章包括创建 有来商城youlai-mall 这个项目的目的,想给那些真的想提升自己或者迷茫的人(包括自己- ...

  3. 2021版的思维导图MindManager 安装激活以及换机教程

    思维导图软件MindManager更新版本啦,相信细心的小伙伴应该已经发现了,MindManager最新版的名称变成了MindManager Windows 21,并且更新了很多新功能,点击查看Min ...

  4. 思维导图哪款好用?怎么借助MindManager 做旅游计划

    世界那么大,想不想去看看!想不想来一场说走就走的旅行?尤其是在新冠的笼罩下, 2020年已经过去四分之三,国内疫情已经基本得到了控制,接下来的日子里你想出门好好玩玩吗? 说走就走的旅游虽然美好,但是你 ...

  5. word教程字体和段落设置

    放大/缩小字号:1.选中文字-点击"大A"或"小A" 2.同时摁着ctrl+shift+>/ctrl+shift+<即可 设置标题与正文间距:鼠标放 ...

  6. Spring 事件监听机制及原理分析

    简介 在JAVA体系中,有支持实现事件监听机制,在Spring 中也专门提供了一套事件机制的接口,方便我们实现.比如我们可以实现当用户注册后,给他发送一封邮件告诉他注册成功的一些信息,比如用户订阅的主 ...

  7. PHP获取数组中重复值的键值

    $array = array ( 0=>'a', 1=>'b', 2=>'a', 5=>'b', 6=>'c', 40=>'d' ); $keyarr =[];$r ...

  8. Django rest framework 基础

    01: Django rest framework 基础 ​ ​ 1.1 什么是RESTful 1. REST与技术无关,代表的是一种软件架构风格(REST是Representational Stat ...

  9. python批量生成SQL语句

    1,首先写一条能运行成功插入SQL的语句 INSERT INTO sign_guest(realname,phone,email,sign,event_id)VALUES("jack&quo ...

  10. sentinel配置

    登陆接口 QPS5,异常0.8,熔断10s 1.异地登陆同省逻辑降级security 2.可疑用户判断certification 3.是否是危险设备判断account 4.是否是自动化imei,ime ...