在之前的文章之中我們決議了一下 Spring Cloud 只需要在 RestTemplate 型別的 Spring Bean 上面添加一個 @LoadBalanced 注解,并且通過 RestTemplate 以 http://serviceId/訪問路徑 就可以訪問真實服務的地址 http://lolcahost:埠/訪問路徑,同樣的 Nepxion Discovery 需要實作服務的灰度發布,也對 Spring Cloud 的負載均衡進行了擴展,基于 Nepxion Discovery 版本為:6.3.5-SNAPSHOT,
1、Nacos 負載均衡實作
Spring Cloud 對于負載均衡默認并沒有對 Nacos 的實作,那么我們就來看一下 Nacos 是如何實作負載均衡的,具體實作類是 NacosRule,在使用 nacos 作為注冊中心時,并沒有使用這個策略,
public class NacosRule extends AbstractLoadBalancerRule {
private static final Logger LOGGER = LoggerFactory.getLogger(NacosRule.class);
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Autowired
private NacosServiceManager nacosServiceManager;
@Override
public Server choose(Object key) {
try {
String clusterName = this.nacosDiscoveryProperties.getClusterName();
String group = this.nacosDiscoveryProperties.getGroup();
DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
String name = loadBalancer.getName();
NamingService namingService = nacosServiceManager
.getNamingService(nacosDiscoveryProperties.getNacosProperties());
List<Instance> instances = namingService.selectInstances(name, group, true);
if (CollectionUtils.isEmpty(instances)) {
LOGGER.warn("no instance in service {}", name);
return null;
}
List<Instance> instancesToChoose = instances;
if (StringUtils.isNotBlank(clusterName)) {
List<Instance> sameClusterInstances = instances.stream()
.filter(instance -> Objects.equals(clusterName,
instance.getClusterName()))
.collect(Collectors.toList());
if (!CollectionUtils.isEmpty(sameClusterInstances)) {
instancesToChoose = sameClusterInstances;
}
else {
LOGGER.warn(
"A cross-cluster call occurs,name = {}, clusterName = {}, instance = {}",
name, clusterName, instances);
}
}
Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToChoose);
return new NacosServer(instance);
}
catch (Exception e) {
LOGGER.warn("NacosRule error", e);
return null;
}
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
}
這個物件里面注入了 NacosDiscoveryProperties 配置屬性以及 NacosServiceManager 服務管理器,首先通過服務組(沒有配置就是 DEFAULT),以及服務的名稱獲取到服務實體的串列,如果服務的配置資訊里面包含服務的集群資訊(clusterName),就會過濾服務實體串列,如果串列里面有當前群集的資訊,如果過濾后的串列不為空就使用同集群的服務,否則還是使用未過濾之前的服務實體串列,最后通過權重隨機演算法獲取到一個服務資訊,
在 Nacos 的 Spring Cloud 自動配置依賴模塊 spring-cloud-starter-alibaba-nacos-discovery 里面自定義了 RibbonClient 客戶端相關的服務配置,
RibbonNacosAutoConfiguration.java
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@ConditionalOnBean(SpringClientFactory.class)
@ConditionalOnRibbonNacos
@ConditionalOnNacosDiscoveryEnabled
@AutoConfigureAfter(RibbonAutoConfiguration.class)
@RibbonClients(defaultConfiguration = NacosRibbonClientConfiguration.class)
public class RibbonNacosAutoConfiguration {
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnRibbonNacos
public class NacosRibbonClientConfiguration {
@Autowired
private PropertiesFactory propertiesFactory;
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config,
NacosDiscoveryProperties nacosDiscoveryProperties) {
if (this.propertiesFactory.isSet(ServerList.class, config.getClientName())) {
ServerList serverList = this.propertiesFactory.get(ServerList.class, config,
config.getClientName());
return serverList;
}
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(config);
return serverList;
}
@Bean
@ConditionalOnMissingBean
public NacosServerIntrospector nacosServerIntrospector() {
return new NacosServerIntrospector();
}
}
在這里它使用了的是基于 Nacos 注冊中心,NacosServerList實作 ServerList 介面對 Nacos 里面服務資訊串列的獲取,同時在 Spring 容器中添加了 ServerIntrospector 的服務自省實作類 NacosServerIntrospector 可以獲取到這個服務是否安全的(基于 https 協議) 以及服務資訊的元資料,
2、Nepxion Discovery 的擴展
Nepxion Discovery 對負載均衡的擴展其實就是對 IRule 介面實作的擴展,這里其實就服務灰度發布的真正實作,DiscoveryClient 根據服務 ID 獲取到這個服務所有暴露的可用的服務串列,通過負載均衡里面的策略選擇一個合適的服務進行呼叫,最終就呼叫到Nepxion Discovery 對負載均衡的擴展其實就是對 IRule 介面實作的擴展
下面就是Nepxion Discovery 對 IRule 這個策略介面的實作:

下面我們看一下擴展策略介面的作用:
| 實作類 | 策略描述 | 實作說明 |
|---|---|---|
PredicateBasedRuleDecorator | 抽象類,繼承PredicateBasedRule并且重寫了 IRule#choose,支持 version權重和 region 權重 | 分別從 header 里面和遠程配置中心獲取version權重和 region 權重,優先級:header > 配置中心 |
DiscoveryEnabledBaseRule | 繼承PredicateBasedRuleDecorator,復合判斷 server 的可用性選擇 server 以及通過灰度引數選擇 server | 使用 ZoneAvoidancePredicate 和 DiscoveryEnabledBasePredicate 來判斷是否選擇某個 server,前一個判斷判定一個 zone 的運行性能是否可用,剔除不可用的 zone(的所有 server),DiscoveryEnabledBasePredicate用于過濾掉不滿足灰度條件的 server |
ZoneAvoidanceRuleDecorator | 繼承 ZoneAvoidanceRule并且重寫了 IRule#choose,支持 version權重和 region 權重 | 分別從 header 里面和遠程配置中心獲取version權重和 region 權重,優先級:header > 配置中心 |
DiscoveryEnabledZoneAvoidanceRule | 繼承ZoneAvoidanceRuleDecorator,復合判斷 server 的可用性選擇 server以及通過灰度引數選擇 server | 使用 AvailabilityPredicate 和 DiscoveryEnabledZoneAvoidancePredicate 來判斷是否選擇某個 server,前一個判斷判定一個 Server 是否可用,剔除不可用的 Server,DiscoveryEnabledBasePredicate用于過濾掉不滿足灰度條件的 server |
在 Nepxion Discovery 框架針對 Robbin 的負載均衡配置有 StrategyLoadBalanceConfiguration 和 PluginLoadBalanceConfiguration 這兩個配置類,
StrategyLoadBalanceConfiguration.java
@Configuration
@AutoConfigureBefore(RibbonClientConfiguration.class)
public class StrategyLoadBalanceConfiguration {
@Autowired
private ConfigurableEnvironment environment;
@RibbonClientName
private String serviceId = "client";
@Autowired
private PropertiesFactory propertiesFactory;
@Autowired
private PluginAdapter pluginAdapter;
@Autowired(required = false)
private DiscoveryEnabledAdapter discoveryEnabledAdapter;
@Bean
public IRule ribbonRule(IClientConfig config) {
if (this.propertiesFactory.isSet(IRule.class, serviceId)) {
return this.propertiesFactory.get(IRule.class, config, serviceId);
}
boolean zoneAvoidanceRuleEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_ZONE_AVOIDANCE_RULE_ENABLED, Boolean.class, Boolean.TRUE);
if (zoneAvoidanceRuleEnabled) {
DiscoveryEnabledZoneAvoidanceRule discoveryEnabledRule = new DiscoveryEnabledZoneAvoidanceRule();
discoveryEnabledRule.initWithNiwsConfig(config);
DiscoveryEnabledZoneAvoidancePredicate discoveryEnabledPredicate = discoveryEnabledRule.getDiscoveryEnabledPredicate();
discoveryEnabledPredicate.setPluginAdapter(pluginAdapter);
discoveryEnabledPredicate.setDiscoveryEnabledAdapter(discoveryEnabledAdapter);
return discoveryEnabledRule;
} else {
DiscoveryEnabledBaseRule discoveryEnabledRule = new DiscoveryEnabledBaseRule();
DiscoveryEnabledBasePredicate discoveryEnabledPredicate = discoveryEnabledRule.getDiscoveryEnabledPredicate();
discoveryEnabledPredicate.setPluginAdapter(pluginAdapter);
discoveryEnabledPredicate.setDiscoveryEnabledAdapter(discoveryEnabledAdapter);
return discoveryEnabledRule;
}
}
}
下面是 PluginLoadBalanceConfiguration 配置類:
PluginLoadBalanceConfiguration
@Configuration
@AutoConfigureAfter(RibbonClientConfiguration.class)
public class PluginLoadBalanceConfiguration {
@RibbonClientName
private String serviceId = "client";
@Autowired
private PropertiesFactory propertiesFactory;
@Autowired
private LoadBalanceListenerExecutor loadBalanceListenerExecutor;
@Bean
@ConditionalOnMissingBean
public IRule ribbonRule(IClientConfig config) {
if (this.propertiesFactory.isSet(IRule.class, serviceId)) {
return this.propertiesFactory.get(IRule.class, config, serviceId);
}
ZoneAvoidanceRuleDecorator rule = new ZoneAvoidanceRuleDecorator();
rule.initWithNiwsConfig(config);
return rule;
}
@Bean
public ILoadBalancer ribbonLoadBalancer(IClientConfig config, ServerList<Server> serverList, ServerListFilter<Server> serverListFilter, IRule rule, IPing ping, ServerListUpdater serverListUpdater) {
if (this.propertiesFactory.isSet(ILoadBalancer.class, serviceId)) {
return this.propertiesFactory.get(ILoadBalancer.class, config, serviceId);
}
ZoneAwareLoadBalancer<?> loadBalancer = new ZoneAwareLoadBalancer<>(config, rule, ping, serverList, serverListFilter, serverListUpdater);
loadBalanceListenerExecutor.setLoadBalancer(loadBalancer);
return loadBalancer;
}
}
PluginLoadBalanceConfiguration 的類上面的配置是@AutoConfigureAfter(RibbonClientConfiguration.class),所以它的初始化順序在 RibbonClientConfiguration 這個Spring Cloud Ribbon 原始配置類之后,而StrategyLoadBalanceConfiguration 類上面的配置是 @AutoConfigureBefore(RibbonClientConfiguration.class),所以它初始化順序在RibbonClientConfiguration 這個Spring Cloud Ribbon 原始配置類之前,那么三個配置類的初始化順序為:
StrategyLoadBalanceConfiguration ===> RibbonClientConfiguration ===> PluginLoadBalanceConfiguration
并且這三個配置類里面都配置了IRule 這個負載均衡策略,所以生效的就是 StrategyLoadBalanceConfiguration 里面配置的這個策略,默認采用 DiscoveryEnabledZoneAvoidanceRule 這個策略,PluginLoadBalanceConfiguration 和 RibbonClientConfiguration 都配置了 ILoadBalancer 這個型別的 bean,雖然 RibbonClientConfiguration 的初始化順序先于PluginLoadBalanceConfiguration ,但是 RibbonClientConfiguration 配置的 ILoadBalancer 上面標注了 @ConditionalOnMissingBean 注解,這樣 PluginLoadBalanceConfiguration里面的定義ILoadBalancer 這個型別的 Spring bean 就會生效,而RibbonClientConfiguration里面定義的ILoadBalancer 這個型別的 Spring bean 就不會生效,
3、負載均衡對灰度發布的支持
從上面的分析中我們可以得出結論,在使用 Nepxion Discovery 進行服務灰度發布的時候進行服務選擇會使用 DiscoveryEnabledZoneAvoidanceRule這個策略,首先這個策略擴展了Server choose(Object key) 方法,也就是分別從 header 里面和遠程配置中心獲取version權重和 region 權重,并且優先級:header > 配置中心,如果配置了就會通過 AbstractMapWeightRandomLoadBalance 的兩個實作類 StrategyMapWeightRandomLoadBalance 與 RuleMapWeightRandomLoadBalance 這兩個負載均衡器進行服務權重選擇,
當沒有設定version權重和 region 權重時,DiscoveryEnabledZoneAvoidanceRule 就會通過 DiscoveryEnabledZoneAvoidancePredicate#apply 進行服務的選擇,其實它最侄訓呼叫到 DefaultDiscoveryEnabledAdapter#apply 方法,
DefaultDiscoveryEnabledAdapter#apply
public class DefaultDiscoveryEnabledAdapter implements DiscoveryEnabledAdapter {
@Override
public boolean apply(Server server) {
boolean enabled = applyEnvironment(server);
if (!enabled) {
return false;
}
enabled = applyRegion(server);
if (!enabled) {
return false;
}
enabled = applyAddress(server);
if (!enabled) {
return false;
}
enabled = applyIdBlacklist(server);
if (!enabled) {
return false;
}
enabled = applyAddressBlacklist(server);
if (!enabled) {
return false;
}
enabled = applyVersion(server);
if (!enabled) {
return false;
}
return applyStrategy(server);
}
......
}
從上面的引數我們就可以看到灰度發布支持的緯度包含:
- 版本權重
- Region 權重
- 環境
- Region
- 地址
- ID 黑名單
- 地址黑名單
- 版本
- 自定義策略
我們再來對比一下 Nepxion Discovery 官網 上面支持灰度的定義的引數,是不是和我們上面提到的維度基本相同,

以上就是 Nepxion Discovery 對 Spring Cloud 負載均衡擴展實作灰度發布的實作,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/232025.html
標籤:java
上一篇:java排序之冒泡排序和選擇排序
