灰度实体类
@Datapublic static class NewSwitch{//是否开启灰度,true是,false否Boolean enable;//灰度基数,-1的时候默认为全部开启灰度Long divisor;//灰度比例 参数对divisor取余小于等于mod命中灰度Long mod;//白名单,优先判断白名单List<String> whiteList;}
灰度配置
# 开关配置
switchConfig:orderSwitch:#是否开启灰度,true是,false否enable: true#灰度基数,-1的时候默认为全部开启灰度divisor: 100#灰度比例 参数对divisor取余小于mod命中灰度mod: 1#白名单,优先判断白名单whiteList:- 1- 2
配置类
@Component
@RefreshScope
@Data
@ConfigurationProperties("switch-config")
public class SwitchConfig {private NewSwitch orderSwitch;//适用于根据指定id或标识灰度,白名单可以是用户id,手机号啥的public boolean isNewSwitch(NewSwitch newSwitch, Long mod, String white) {if(newSwitch==null){return false;}if(!Boolean.TRUE.equals(newSwitch.enable)){return false;}if(newSwitch.divisor==-1){return true;}if(!StringUtils.isEmpty(white)){if(newSwitch.whiteList.contains(white)){return true;}}if(newSwitch.divisor==0){return false;}if(mod==null){mod=getRandomNumber(newSwitch.divisor.intValue());}Long res=mod%newSwitch.divisor;if(res<newSwitch.mod){return true;}return false;}//适用于随机灰度 按配置的比例灰度public boolean isNewSwitch(NewSwitch newSwitch) {return isNewSwitch(newSwitch,null,null);}//适用于根据指定id或标识灰度public boolean isNewSwitch(NewSwitch newSwitch,Long mod) {return isNewSwitch(newSwitch,mod,null);}//有需要可以再加个白名单灰度@Datapublic static class NewSwitch{//是否开启灰度,true是,false否Boolean enable;//灰度基数,-1的时候默认为全部开启灰度Long divisor;//灰度比例 参数对divisor取余小于等于mod命中灰度Long mod;//白名单,优先判断白名单List<String> whiteList;}
}
灰度使用
public class OrderTest {@Autowiredprivate SwitchConfig switchConfig;public void switchTest { if(switchConfig.isNewSwitch(switchConfig.getOrderToHtapSwitch())){//todo new}else{//todo old}}