今天给大家分享一篇我在学习Nacos想用它做灰度发布的思路分享。
什么是灰度发布请看如下链接:baike.baidu.com/item/灰度发布/7…
那么进入正题,在netflix全家桶相继凉凉后,Ribbon组件确一直坚挺包括在Spring Cloud Alibaba Nacos中也在使用。其实要基于Nacos做灰度发布,也是在Ribbon上做手脚。
第一步扩展Metadata Predicate
public abstract class DiscoveryEnabledPredicate extends AbstractServerPredicate {
@Override
public boolean apply(@Nullable PredicateKey input) {
//由于NacosServer继承了Ribbon的Server,那么扩展成其他配置中心同理
return input != null
&& input.getServer() instanceof NacosServer
&& apply((NacosServer) input.getServer());
}
protected abstract boolean apply(NacosServer nacosServer);
}
复制代码
public class MetadataAwarePredicate extends DiscoveryEnabledPredicate{
@Override
protected boolean apply(NacosServer nacosServer) {
//根据客户端传入的版本号进行过滤,此处可自行设计扩展
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder
.getRequestAttributes()).getRequest();
String versionNo = request.getHeader("version");
Map<String,String> versionMap = new HashMap<>();
versionMap.put("version",versionNo);
final Set<Map.Entry<String,String>> attributes =
Collections.unmodifiableSet(versionMap.entrySet());
final Map<String,String> metadata = nacosServer.getInstance().getMetadata();
return metadata.entrySet().containsAll(attributes);
}
}
复制代码
第二步扩展Metadata Rule
public abstract class DiscoveryEnabledRule extends PredicateBasedRule {
private final CompositePredicate predicate;
public DiscoveryEnabledRule(DiscoveryEnabledPredicate discoveryEnabledPredicate) {
Assert.notNull(discoveryEnabledPredicate, "Parameter 'discoveryEnabledPredicate' can't be null");
this.predicate = createCompositePredicate(discoveryEnabledPredicate,new AvailabilityPredicate(this,null));
}
@Override
public AbstractServerPredicate getPredicate() {
return this.predicate;
}
private CompositePredicate createCompositePredicate(DiscoveryEnabledPredicate discoveryEnabledPredicate,
AvailabilityPredicate availabilityPredicate) {
return CompositePredicate.withPredicates(discoveryEnabledPredicate, availabilityPredicate)
.build();
}
}
复制代码
public class MetadataAwareRule extends DiscoveryEnabledRule{
public MetadataAwareRule(){
this(new MetadataAwarePredicate());
}
public MetadataAwareRule(DiscoveryEnabledPredicate predicate) {
super(predicate);
}
}
复制代码
第三步丢进Spring容器
@Configuration
public class RibbonDiscoveryRuleAutoConfiguration {
@Bean
public DiscoveryEnabledRule metadataAwareRule(){
return new MetadataAwareRule();
}
}
复制代码
最后
灰度发布其实是一个挺复杂的系统,上述代码只是给大家提供一丢丢思路,本菜也在学习中。
同时给大家推荐一个相当不错的灰度发布框架(军哥的作品),github.com/Nepxion/Dis…
另外,本菜最近失业了,有需要搬砖的联系我啊,坐标:广州、长沙即可(专业研究CRUD 3-4年)