Spring Cloud Alibaba Nacos 之 灰度釋出(思路分享)
今天給大家分享一篇我在學習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(DiscoveryEnabledPredicatediscoveryEnabledPredicate) { 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年)