Spring Cloud Alibaba Nacos 之 灰度發佈(思路分享)

今天給你們分享一篇我在學習Nacos想用它作灰度發佈的思路分享。git

什麼是灰度發佈請看以下連接:baike.baidu.com/item/灰度發佈/7…github

那麼進入正題,在netflix全家桶相繼涼涼後,Ribbon組件確一直堅挺包括在Spring Cloud Alibaba Nacos中也在使用。其實要基於Nacos作灰度發佈,也是在Ribbon上作手腳。bash

第一步擴展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();
    }
}
複製代碼

最後

灰度發佈實際上是一個挺複雜的系統,上述代碼只是給你們提供一丟丟思路,本菜也在學習中。app

同時給你們推薦一個至關不錯的灰度發佈框架(軍哥的做品),github.com/Nepxion/Dis…框架

另外,本菜最近失業了,有須要搬磚的聯繫我啊,座標:廣州、長沙便可(專業研究CRUD 3-4年)ide

相關文章
相關標籤/搜索