0

SpringCloud项目开发中实用技巧总结

 1 month ago
source link: https://www.51cto.com/article/784794.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

环境:SpringBoot2.7.12 + SpringCloud2021.0.7

1. 日志配置

如果使用 Spring Boot 配置日志设置,则应将此配置放在 bootstrap.[yml | properties] 中,以便将其应用于所有事件。注意:为了让 Spring Cloud 正确初始化日志配置,不能使用自定义前缀。例如,在初始化日志系统时,Spring Cloud 无法识别使用 custom.loggin.logpath 的情况。

2. 配置发生变化

应用程序会侦听EnvironmentChangeEvent事件,并以几种标准方式对变化做出反应。当EnvironmentChangeEvent事件被监听到时,它将收到发生变化的keys,应用程序将会做如下处理:

  • 重新绑定@ConfigurationProperties的Bean对象
    监听器:ConfigurationPropertiesRebinder
  • 为 logging.level.* 中的任何属性设置日志记录器级别。
    监听器:LoggingRebinder

你也可以自定义监听EnvironmentChangeEvent事件

@Component
public class PackApplicationEventListener implements ApplicationListener<EnvironmentChangeEvent> {


  @Override
  public void onApplicationEvent(EnvironmentChangeEvent event) {
    System.out.println(event.getKeys()) ;
  }
}

3. @RefreshScope不是什么都能刷新

那些只能初始化一次的 Bean 上使用 @RefreshScope 注解。如果某个 Bean 是 "不可变"的,则必须使用 @RefreshScope 注解或通过如下配置指明完整的类名:

spring:
  cloud: 
    refresh: 
      extra-refreshable: com.pack.PackUser

如果你使用的数据源 Bean 是 HikariDataSource,则无法刷新。这是 spring.cloud.refresh.never-refreshable 的默认值。如果需要刷新,请选择不同的数据源实现。

4. 加密与解密

Spring Cloud 有一个环境预处理器,用于在本地解密属性值。可以使用 {cipher}* 形式的加密值,只要存在有效的密钥,它们就会在主应用程序上下文获得环境设置之前被解密。要在应用程序中使用加密功能,需要在类路径中包含 Spring Security RSA(Maven 坐标:org.springframework.security:spring-security-rsa)。

#加密配置
encrypt:
  key: aaaabbbbccccdddd
  salt: dead
#---
#加密关键信息
db:
  password: '{cipher}6c05a3e62aa1f71b814fd283fc15197ec18a83b67d9da27dcb63c1b3925d68c1'

这里默认使用的AES算法,所以通过如下方式生成密文即可

TextEncryptor textEncryptor = new EncryptorFactory("xxx").create("xxxx") ;
textEncryptor.encrypt(...)

5. Acturator接口

对于 Spring Boot Actuator 应用程序,还提供了一些额外的管理端点:

  • POST 到 /actuator/env,以更新环境并重新绑定 @ConfigurationProperties 和日志级别。要启用此端点,必须设置 management.endpoint.env.post.enabled=true。
  • /actuator/refresh 重新加载引导带上下文并刷新 @RefreshScope Bean。
  • /actuator/restart 关闭 ApplicationContext 并重新启动(默认禁用)。
  • /actuator/pause 和 /actuator/resume,用于调用生命周期方法(ApplicationContext 上的 stop() 和 start())。

6. 自定义属性源

通过 spring.factories添加 PropertySourceLocator 类型的 Bean 来添加其他属性源。如下示例:

public class CustomPropertySourceLocator implements PropertySourceLocator {


  @Override
  public PropertySource<?> locate(Environment environment) {
    Map<String, Object> values = new HashMap<>() ;
    values.put("config.mq.queue", "pack.test.queue") ;
    MapPropertySource source = new MapPropertySource("PACK", values) ;
    return source ;
  }


}

在spring.factories中添加如下配置

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.pack.CustomPropertySourceLocator

以上是本篇文章的全部内容,希望对你有帮助。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK