spring動態讀取配置中心配置

背景

在flink任務流中使用flink+spring+nacos實現動態配置的目的,但是在初始化數據庫配置參數和redis等配置參數的時候,不通過讀取本地properties文件。

配置

<content:property-placeholder location="application.properties"></content:property-placeholder>

配置變更

    <bean id="localProperties" class="com.example.config.Config" init-method="init" />
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="localProperties"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>
public class Config extends Properties {

    public Config() {
    }

    public void init() {
        log.info("獲取nacos文件信息...");
        String group = "DEFAULT_GROUP";
        String dataId = "flink-config.properties";
        try {
            Map<String, String> map = System.getenv();
            String serverAddr = map.getOrDefault("NACOS_SERVER_ADDR", "");
            log.info("讀取環境變量NACOS_SERVER_ADDR:{}", serverAddr);
            Properties pros = new Properties();
            pros.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
            ConfigService configService = NacosFactory.createConfigService(pros);
            String content = configService.getConfig(dataId, group, 3000);
            log.info("獲取到配置文件信息:{}", content);
            try {
                this.load(new StringReader(content));
            } catch (IOException | NullPointerException e) {
                log.error("解析配置文件異常:{}", e.getMessage(), e);
            }
            log.info("當前spring文件配置:{}", JSON.toJSONString(this));
        } catch (NacosException e) {
            log.info("獲取配置異常:{}", e.getMessage(), e);
        }
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章