【问题标题】:Read properties from properties file in a regular interval at runtime在运行时定期从属性文件中读取属性
【发布时间】:2020-11-19 22:42:32
【问题描述】:

有一些属性,我想间隔读取这些属性,如果属性有任何更新,我会在此基础上采取一些行动。

    @Value("${sms.smpp.country.list:{}}")
    private String smppCountryList;

    @Value("${sms.smpp.country.config.list:{}}")
    private String smppCountryConfigList;

    @Value("${sms.smpp.properties.file.location:{}}")
    private String propertiesFileLocation;
     

我已经编写了一个代码来使用 cron 读取属性,这里是代码。

    @Scheduled(cron = "0 0/7 * * * ?")
    public Properties readPropertiesFile() {
        Properties prop = null;
        
        try (InputStream input = new FileInputStream(propertiesFileLocation)) {
            prop = new Properties();
            prop.load(input);
        } catch (IOException ex) {
            logger.info("[SMPP] [CONFIG CRON] Exception occurred while reading the properties file: [{}]",ex.getMessage());
        }
        
        return prop;
    }

代码被 cron 调用,或者我也可以在文件上写一个 onFileChangeHandler。

但是有什么简单而优雅的方法可以做到这一点,比如spring可以处理吗?

【问题讨论】:

  • 在您当前的解决方案中,@Value 注解的属性是否会自动刷新?我会说不,但我想知道。
  • @RUARO Thibault 不,这些值没有被刷新,但在读取属性文件后我正在更新这些值。

标签: java spring properties-file


【解决方案1】:

编辑 1:查看您的代码,我想指出一件事,即使您连续运行 cron 作业,@Value 变量也不会更新为更新值

如果您想定期查找配置更改,Spring Boot 带有一个 spring 配置服务器。

您的微服务将与配置保持同步,而无需编写任何代码行。

看看 Spring Cloud Config Server

【讨论】:

  • 我在使用 cron 读取 @Value 变量后更新它。
  • 试试Spring cloud Config Server(Spring推荐这样做),你能分享一下你是如何更新值的
  • 我正在更新这样的值:smppCountryList = readPropertiesFile.get(sms.smpp.country.list)
  • 这将是大量的手工工作。今天它是一个文件,当它是 1000 时,它会产生很多问题。我建议不要这样做,而是使用 Spring Cloud Config Server。如果它有助于投票!
  • 是的@Shivendra,Spring Cloud Config Server 会有所帮助,但我不能使用它,我想知道一些其他方式,比如一些注释或配置更改或类似的东西。
【解决方案2】:

你必须使用 Spring Config Server,如果你想更新带有 @Value 注释的属性,你需要使用 @RefreshScope 来注释类。

【讨论】:

    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    相关资源
    最近更新 更多