背景

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

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐