在网上查找一下,好像没有现成的解决方法,在此记录一下,供你们参考实现。ide
前提Spring boot 工程,使用的是yml 文件格式(其余格式同样的,换一下加载类),整体解决思路,启动定时器,定时检测外部文件是否有修改。若是文件被修改,获取配置文件内容后进行业务处理。测试
一. 定时器get
public void init() { scheduled = Executors.newScheduledThreadPool(1); scheduled.scheduleAtFixedRate(new Runnable() { @Override public void run() { refresh(); } }, 1, 10, TimeUnit.SECONDS); //测试时间比较短,根据实际需求修改,如5分钟 }
二. 刷新查看it
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,类变量io
long lastModified = 0; ScheduledExecutorService scheduled; @Value("${***.file.path:NONE}") String filePath;
获取到数据后,直接操做Environment ,仍是保存本地类变量均可以操做,ast
PropertySource<LinkedHashMap> ,根据实际格式处理,PropertySource<?>变量