监听 apollo 配置变化

监听 apollo 配置 cleanPrecisionVersion 变化的类

源码

@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class InitApolloConfigure implements CommandLineRunner {
     

	// 内存缓存
    private volatile ConcurrentHashMap<String, List<String>> cleanPrecisionMap = new ConcurrentHashMap();
    // apollo 中配置 cleanPrecision 版本的 KEY
    private static final String CLEAN_PRECISION_VERSION = "cleanPrecisionVersion";
    //inject config for namespace application
    @ApolloConfig
    private Config config;
    @Reference(version = "${dubbo.order.application.version}")
    private ICleanPrecisionConfigBiz cleanPrecisionConfigBiz;

    @Override
    public void run(String... args) throws Exception{
     
        // 加载 namespace application 的配置
        Set<String> configs = config.getPropertyNames();
        if (CollectionUtils.isNotEmpty(configs)) {
     
            // 项目启动,加载数据到内存中
            setInitCleanPrecisionMap();
            monitorApolloConfigurationChange(config);
        }

    }

    private void setInitCleanPrecisionMap() {
     
        List<CleanPrecisionConfig> list = cleanPrecisionConfigBiz.getCleanPrecisionConfigList();
        if (CollectionUtils.isEmpty(list)) {
     
            // 手动抛出运行时异常
            String initCleanPrecisionMapMsg = "项目启动,查询 DB 为空!" + " 服务器 IP:" + IpUtil.getIp();
            throw new RuntimeException(initCleanPrecisionMapMsg);
        } else {
     
            setMap(list);
        }

    }

    private void monitorApolloConfigurationChange(Config config) {
     
        config.addChangeListener(configChangeEvent -> {
     
            // 监听 apollo 配置中发生变化的 KEY
            Set<String> keys = configChangeEvent.changedKeys();
            if (CollectionUtils.isNotEmpty(keys) && keys.contains(CLEAN_PRECISION_VERSION)) {
     
                // KEY 变化,重新加载数据到内存中
                setUpdateCleanPrecisionMap();
            }
        });

    }

}

参考文档

  • springboot-监听apollo配置

你可能感兴趣的:(middleware,apollo)