spring动态读取配置中心配置

1 篇文章 0 订阅
1 篇文章 0 订阅

背景

在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);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值