如何在 Java EE 和 Spring Boot 中热重载属性?

新手上路,请多包涵

许多内部解决方案浮现在脑海中。就像在数据库中拥有属性并每 N 秒轮询一次。然后还要检查 .properties 文件的时间戳修改并重新加载它。

但是我一直在查看 Java EE 标准和 spring boot 文档,但我似乎找不到一些最好的方法。

我需要我的应用程序读取属性文件(或环境变量或数据库参数),然后能够重新读取它们。生产中使用的最佳实践是什么?

一个正确的答案至少会解决一个场景(Spring Boot 或 Java EE)并提供一个关于如何让它在另一个场景上工作的概念线索

原文由 David Hofmann 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 816
2 个回答

经过进一步研究, 必须仔细考虑重载属性。例如,在 Spring 中,我们可以毫无问题地重新加载属性的“当前”值。但。在上下文初始化时根据 application.properties 文件中存在的值(例如数据源、连接池、队列等)初始化资源时,必须特别小心。

注意

用于 Spring 和 Java EE 的抽象类并不是干净代码的最佳示例。但它易于使用,并且确实满足了以下基本初始要求:

  • 除了 Java 8 类之外,不使用外部库。
  • 只有一个文件可以解决问题(Java EE 版本约 160 行)。
  • 使用文件系统中可用的标准 Java 属性 UTF-8 编码文件。
  • 支持加密属性。

对于春季启动

此代码有助于在不使用 Spring Cloud Config 服务器的情况下热重载 application.properties 文件(这对于某些用例来说可能有点矫枉过正)

您可以复制和粘贴这个抽象类(好东西:D)这 是从这个 SO answer 派生的代码

// imports from java/spring/lombok
public abstract class ReloadableProperties {

  @Autowired
  protected StandardEnvironment environment;
  private long lastModTime = 0L;
  private Path configPath = null;
  private PropertySource<?> appConfigPropertySource = null;

  @PostConstruct
  private void stopIfProblemsCreatingContext() {
    System.out.println("reloading");
    MutablePropertySources propertySources = environment.getPropertySources();
    Optional<PropertySource<?>> appConfigPsOp =
        StreamSupport.stream(propertySources.spliterator(), false)
            .filter(ps -> ps.getName().matches("^.*applicationConfig.*file:.*$"))
            .findFirst();
    if (!appConfigPsOp.isPresent())  {
      // this will stop context initialization
      // (i.e. kill the spring boot program before it initializes)
      throw new RuntimeException("Unable to find property Source as file");
    }
    appConfigPropertySource = appConfigPsOp.get();

    String filename = appConfigPropertySource.getName();
    filename = filename
        .replace("applicationConfig: [file:", "")
        .replaceAll("\\]$", "");

    configPath = Paths.get(filename);

  }

  @Scheduled(fixedRate=2000)
  private void reload() throws IOException {
      System.out.println("reloading...");
      long currentModTs = Files.getLastModifiedTime(configPath).toMillis();
      if (currentModTs > lastModTime) {
        lastModTime = currentModTs;
        Properties properties = new Properties();
        @Cleanup InputStream inputStream = Files.newInputStream(configPath);
        properties.load(inputStream);
        environment.getPropertySources()
            .replace(
                appConfigPropertySource.getName(),
                new PropertiesPropertySource(
                    appConfigPropertySource.getName(),
                    properties
                )
            );
        System.out.println("Reloaded.");
        propertiesReloaded();
      }
    }

    protected abstract void propertiesReloaded();
}

然后创建一个 bean 类,允许从使用抽象类的 applicatoin.properties 检索属性值

@Component
public class AppProperties extends ReloadableProperties {

    public String dynamicProperty() {
        return environment.getProperty("dynamic.prop");
    }
    public String anotherDynamicProperty() {
        return environment.getProperty("another.dynamic.prop");
    }
    @Override
    protected void propertiesReloaded() {
        // do something after a change in property values was done
    }
}

确保将 @EnableScheduling 添加到您的 @SpringBootApplication

 @SpringBootApplication
@EnableScheduling
public class MainApp  {
   public static void main(String[] args) {
      SpringApplication.run(MainApp.class, args);
   }
}

现在您可以在任何需要的地方 自动 连接 AppProperties Bean。只要确保 始终 调用其中的方法而不是将其值保存在变量中即可。并确保重新配置使用可能不同的属性值初始化的任何资源或 bean。

目前,我只使用外部和默认找到的 ./config/application.properties 文件对此进行了测试。

对于 Java EE

我制作了一个通用的 Java SE 抽象类来完成这项工作。

你可以复制粘贴这个:

 // imports from java.* and javax.crypto.*
public abstract class ReloadableProperties {

  private volatile Properties properties = null;
  private volatile String propertiesPassword = null;
  private volatile long lastModTimeOfFile = 0L;
  private volatile long lastTimeChecked = 0L;
  private volatile Path propertyFileAddress;

  abstract protected void propertiesUpdated();

  public class DynProp {
    private final String propertyName;
    public DynProp(String propertyName) {
      this.propertyName = propertyName;
    }
    public String val() {
      try {
        return ReloadableProperties.this.getString(propertyName);
      } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
      }
    }
  }

  protected void init(Path path) {
    this.propertyFileAddress = path;
    initOrReloadIfNeeded();
  }

  private synchronized void initOrReloadIfNeeded() {
    boolean firstTime = lastModTimeOfFile == 0L;
    long currentTs = System.currentTimeMillis();

    if ((lastTimeChecked + 3000) > currentTs)
      return;

    try {

      File fa = propertyFileAddress.toFile();
      long currModTime = fa.lastModified();
      if (currModTime > lastModTimeOfFile) {
        lastModTimeOfFile = currModTime;
        InputStreamReader isr = new InputStreamReader(new FileInputStream(fa), StandardCharsets.UTF_8);
        Properties prop = new Properties();
        prop.load(isr);
        properties = prop;
        isr.close();
        File passwordFiles = new File(fa.getAbsolutePath() + ".key");
        if (passwordFiles.exists()) {
          byte[] bytes = Files.readAllBytes(passwordFiles.toPath());
          propertiesPassword = new String(bytes,StandardCharsets.US_ASCII);
          propertiesPassword = propertiesPassword.trim();
          propertiesPassword = propertiesPassword.replaceAll("(\\r|\\n)", "");
        }
      }

      updateProperties();

      if (!firstTime)
        propertiesUpdated();

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

  private void updateProperties() {
    List<DynProp> dynProps = Arrays.asList(this.getClass().getDeclaredFields())
        .stream()
        .filter(f -> f.getType().isAssignableFrom(DynProp.class))
        .map(f-> fromField(f))
        .collect(Collectors.toList());

    for (DynProp dp :dynProps) {
      if (!properties.containsKey(dp.propertyName)) {
        System.out.println("propertyName: "+ dp.propertyName + " does not exist in property file");
      }
    }

    for (Object key : properties.keySet()) {
      if (!dynProps.stream().anyMatch(dp->dp.propertyName.equals(key.toString()))) {
        System.out.println("property in file is not used in application: "+ key);
      }
    }

  }

  private DynProp fromField(Field f) {
    try {
      return (DynProp) f.get(this);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
    return null;
  }

  protected String getString(String param) throws Exception {
    initOrReloadIfNeeded();
    String value = properties.getProperty(param);
    if (value.startsWith("ENC(")) {
      String cipheredText = value
          .replace("ENC(", "")
          .replaceAll("\\)$", "");
      value =  decrypt(cipheredText, propertiesPassword);
    }
    return value;
  }

  public static String encrypt(String plainText, String key)
      throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
    SecureRandom secureRandom = new SecureRandom();
    byte[] keyBytes = key.getBytes(StandardCharsets.US_ASCII);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(key.toCharArray(), new byte[]{0,1,2,3,4,5,6,7}, 65536, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
    byte[] iv = new byte[12];
    secureRandom.nextBytes(iv);
    final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); //128 bit auth tag length
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
    byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
    ByteBuffer byteBuffer = ByteBuffer.allocate(4 + iv.length + cipherText.length);
    byteBuffer.putInt(iv.length);
    byteBuffer.put(iv);
    byteBuffer.put(cipherText);
    byte[] cipherMessage = byteBuffer.array();
    String cyphertext = Base64.getEncoder().encodeToString(cipherMessage);
    return cyphertext;
  }
  public static String decrypt(String cypherText, String key)
      throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
    byte[] cipherMessage = Base64.getDecoder().decode(cypherText);
    ByteBuffer byteBuffer = ByteBuffer.wrap(cipherMessage);
    int ivLength = byteBuffer.getInt();
    if(ivLength < 12 || ivLength >= 16) { // check input parameter
      throw new IllegalArgumentException("invalid iv length");
    }
    byte[] iv = new byte[ivLength];
    byteBuffer.get(iv);
    byte[] cipherText = new byte[byteBuffer.remaining()];
    byteBuffer.get(cipherText);
    byte[] keyBytes = key.getBytes(StandardCharsets.US_ASCII);
    final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(key.toCharArray(), new byte[]{0,1,2,3,4,5,6,7}, 65536, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(128, iv));
    byte[] plainText= cipher.doFinal(cipherText);
    String plain = new String(plainText, StandardCharsets.UTF_8);
    return plain;
  }
}

然后你可以这样使用它:

 public class AppProperties extends ReloadableProperties {

  public static final AppProperties INSTANCE; static {
    INSTANCE = new AppProperties();
    INSTANCE.init(Paths.get("application.properties"));
  }

  @Override
  protected void propertiesUpdated() {
    // run code every time a property is updated
  }

  public final DynProp wsUrl = new DynProp("ws.url");
  public final DynProp hiddenText = new DynProp("hidden.text");

}

如果您想使用编码属性,您可以将其值包含在 ENC() 中,并且将在属性文件的相同路径和名称中搜索用于解密的密码,并添加 .key 扩展名。在此示例中,它将在 application.properties.key 文件中查找密码。

应用程序.properties ->

 ws.url=http://some webside
hidden.text=ENC(AAAADCzaasd9g61MI4l5sbCXrFNaQfQrgkxygNmFa3UuB9Y+YzRuBGYj+A==)

应用程序.properties.key ->

 password aca

对于 Java EE 解决方案的属性值加密,我参考了 Patrick Favre-Bulle 关于 在 Java 和 Android 中使用 AES 进行对称加密的 优秀文章。然后在这个关于 AES/GCM/NoPadding 的 SO 问题中检查密码、块模式和填充。最后,我使 AES 位源自@erickson 在 SO about AES Password Based Encryption 中的出色答案的密码。关于 Spring 中值属性的加密,我认为它们与 Java Simplified Encryption 集成在一起

这是否符合最佳实践条件可能超出范围。这个答案展示了如何在 Spring Boot 和 Java EE 中拥有可重新加载的属性。

原文由 David Hofmann 发布,翻译遵循 CC BY-SA 4.0 许可协议

此功能可以通过使用 Spring Cloud Config Server刷新范围客户端 来实现。

服务器

服务器(Spring Boot 应用程序)提供存储在例如 Git 存储库中的配置:

 @SpringBootApplication
@EnableConfigServer
public class ConfigServer {
  public static void main(String[] args) {
    SpringApplication.run(ConfigServer.class, args);
  }
}

应用程序.yml:

 spring:
  cloud:
    config:
      server:
        git:
          uri: git-repository-url-which-stores-configuration.git

配置文件 configuration-client.properties (在 Git 存储库中):

 configuration.value=Old

客户

客户端(Spring Boot 应用程序)使用 @RefreshScope 注解从配置服务器读取配置:

 @Component
@RefreshScope
public class Foo {

    @Value("${configuration.value}")
    private String value;

    ....
}

引导程序.yml:

 spring:
  application:
    name: configuration-client
  cloud:
    config:
      uri: configuration-server-url

当 Git 存储库中有配置更改时:

 configuration.value=New

通过向 /refresh 端点发送 POST 请求重新加载配置变量:

 $ curl -X POST http://client-url/actuator/refresh

现在您有了新值 New

另外 Foo 类可以通过 RESTful API 如果它更改为 RestController 并具有相应的端点。

原文由 Boris 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题