Spring boot 动态更新外部配置

在网上查找一下,好像没有现成的解决方法,在此记录一下,供大家参考实现。

     前提Spring boot 工程,使用的是yml 文件格式(其他格式一样的,换一下加载类),总体解决思路,启动定时器,定时检测外部文件是否有修改。如果文件被修改,获取配置文件内容后进行业务处理。

一. 定时器

public void init() {

    scheduled = Executors.newScheduledThreadPool(1);
    scheduled.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            refresh();
        }

    }, 1, 10, TimeUnit.SECONDS); //测试时间比较短,根据实际需求修改,如5分钟
}

二. 刷新查看

public void refresh() {

    try {

        if (filePath.equalsIgnoreCase("NONE")) {
            scheduled.shutdown();
        }

        FileSystemResource fileSystemResource = new FileSystemResource(filePath);
        if (lastModified == fileSystemResource.getFile().lastModified()) return;  // 没有修改,直接返回。

        YamlPropertySourceLoader yamLoader = new YamlPropertySourceLoader();
        PropertySource<LinkedHashMap> yamProp = (PropertySource<LinkedHashMap>) yamLoader.load("YamFileName", fileSystemResource, null);

        LinkedHashMap linkedHashMap = yamProp.getSource();
        System.out.println("props FileInputStream size=" + linkedHashMap.size());

        lastModified = fileSystemResource.getFile().lastModified();

    } catch (Exception e) {
        e.printStackTrace();
    }

3,类变量

long lastModified = 0;

ScheduledExecutorService scheduled;

@Value("${***.file.path:NONE}")
String filePath;

获取到数据后,直接操作Environment ,还是保存本地类变量都可以操作,

PropertySource<LinkedHashMap>  ,根据实际格式处理,PropertySource<?>

转载于:https://my.oschina.net/wheatma/blog/1556601

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值