SentinelRulesGenerateConfig 配置类也很简单,主要是利用 Spring 提供的监听器,监听ContextRefreshedEvent事件,即Spring容器初始化完毕,接着利用 ApplicationContext 来获取上面的属性类,然后读取流控规则和熔断规则,最后进行初始化。
/** * Sentinel规则自动生成配置类 * @author winfun * @date 2021/3/4 4:29 下午 **/ @Configuration @ConditionalOnProperty(prefix = "sentinel.rules", name = "enabled", havingValue = "true") @EnableConfigurationProperties({SentinelRulesProperties.class}) public class SentinelRulesGenerateConfig implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware { private ApplicationContext applicationContext; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { SentinelRulesProperties sentinelRulesProperties = this.applicationContext.getBean(SentinelRulesProperties.class); List<SentinelFlowRule> flowRuleList = sentinelRulesProperties.getFlowRuleList(); List<SentinelDegradeRule> degradeRuleList = sentinelRulesProperties.getDegradeRuleList(); final List<FlowRule> flowRules = new ArrayList<>(); final List<DegradeRule> degradeRules = new ArrayList<>(); // 处理流控规则 flowRuleList.forEach(sentinelFlowRule -> { FlowRule flowRule = new FlowRule(); BeanUtils.copyProperties(sentinelFlowRule,flowRule); flowRules.add(flowRule); }); // 处理熔断规则 degradeRuleList.forEach(sentinelDegradeRule -> { DegradeRule degradeRule = new DegradeRule(); BeanUtils.copyProperties(sentinelDegradeRule,degradeRule); degradeRules.add(degradeRule); }); FlowRuleManager.loadRules(flowRules); DegradeRuleManager.loadRules(degradeRules); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }如果大家对这个组件还感兴趣的话,可以到Github上看看:https://github.com/Howinfun/study-in-work-and-life/tree/master/sentinel-rules-sdk