方式一:
#nacos配置文件data.yml: spring:cloud:nacos:discovery:ip: ****.comport: 80datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://*********/database?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNullhikari:idle-timeout: 60000connection-timeout: 60000validation-timeout: 3000login-timeout: 5max-lifetime: 60000maximum-pool-size: 20#项目配置文件bootstrap-test.yml spring:cloud:nacos:discovery:server-addr: http://nacos-headless:8848config:server-addr: http://nacos-headless:8848namespace: TESTfile-extension: ymlextension-configs:- group: DEFAULT_GROUPdata-id: global.yml- group: commondata-id: common.yml- group: datadata-id: db.ymlrefresh: truesm: region: eu-central-1doc: dev-fra-as-api-mongodb-user-root-ZMEAVyQppET6GPfrdsp: dev-fra-as-api-rds-user-root-xp78N8GvtScLmGnrdss: dev-fra-as-pms-rds-v2-readonly-from-sin-user-fra-appplayer-gp3Sex9vbXDU6PL代码package com.yuruo.reco.config;import java.util.HashMap; import java.util.Map;import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource;import com.yuruo.reco.dto.SecretDto; import com.yuruo.reco.utils.JsonUtils;import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;public class SecretsManagerEnvironmentPostProcessor implements EnvironmentPostProcessor {@Overridepublic void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {MutablePropertySources propertySources = environment.getPropertySources();for (PropertySource<?> propertySource : propertySources) {if (propertySource.getName().contains("[bootstrap-" + environment.getActiveProfiles()[0] + ".yml]")) {Region region = Region.of(propertySource.getProperty("sm.region").toString());SecretsManagerClient client = SecretsManagerClient.builder().region(region).credentialsProvider(DefaultCredentialsProvider.create()).build();// 读取配置String primarySecret = getSecretRes(client, propertySource.getProperty("sm.rdsp").toString());SecretDto secret = JsonUtils.stringToJavaObject(primarySecret, SecretDto.class);Map<String, Object> source = new HashMap<>();source.put("spring.datasource.primary.username", secret.getUsername());source.put("spring.datasource.primary.password", secret.getPassword());String secondarySecret = getSecretRes(client, propertySource.getProperty("sm.rdss").toString());secret = JsonUtils.stringToJavaObject(secondarySecret, SecretDto.class);source.put("spring.datasource.secondary.username", secret.getUsername());source.put("spring.datasource.secondary.password", secret.getPassword());String mongosecret = getSecretRes(client, propertySource.getProperty("sm.doc").toString());secret = JsonUtils.stringToJavaObject(mongosecret, SecretDto.class);source.put("spring.data.mongodb.uri", "mongodb://" + secret.getUsername() + ":" + secret.getPassword()+ "@" + secret.getHost() + ":" + secret.getPort());propertySources.addLast(new MapPropertySource("secretsManagerPropertySource", source));}}}private String getSecretRes(SecretsManagerClient client, String secretName) {GetSecretValueRequest request = GetSecretValueRequest.builder().secretId(secretName).build();return client.getSecretValue(request).secretString();}}
方式二:
src/main/resources/META-INF/spring.factories org.springframework.boot.env.EnvironmentPostProcessor=com.yuruo.reco.config.SecretsManagerEnvironmentPostProcessorspring:jpa:properties:hibernate:dialect: org.hibernate.dialect.MySQL8Dialectcloud:nacos:discovery:ip: ****.comport: 80datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://*********/database?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNullusername: ${DB_USETRNAME}password: ${DB_PASSWORD}hikari:idle-timeout: 60000connection-timeout: 60000validation-timeout: 3000login-timeout: 5max-lifetime: 60000maximum-pool-size: 20package com.yuruo.reco.config;import org.apache.commons.lang3.StringUtils; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.env.ConfigurableEnvironment;import com.yuruo.reco.constant.SecretConstant; import com.yuruo.reco.dto.SecretDto; import com.yuruo.reco.utils.JsonUtils;import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;public class SecretsManagerEnvironmentPostProcessor implements EnvironmentPostProcessor {@Overridepublic void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {Region region = Region.of(SecretConstant.SECRET_REGION);SecretsManagerClient client = SecretsManagerClient.builder().region(region).credentialsProvider(DefaultCredentialsProvider.create()).build();String primarySecret = getSecretRes(client, SecretConstant.SECRET_PRIMARY);if(StringUtils.isNotBlank(primarySecret)) {SecretDto secret = JsonUtils.stringToJavaObject(primarySecret, SecretDto.class);System.setProperty("DB1_USETRNAME", secret.getUsername());System.setProperty("DB1_PASSWORD", secret.getPassword());}String secondarySecret = getSecretRes(client, SecretConstant.SECRET_SECONDARY);if(StringUtils.isNotBlank(secondarySecret)) {SecretDto secret = JsonUtils.stringToJavaObject(secondarySecret, SecretDto.class);System.setProperty("DB2_USETRNAME", secret.getUsername());System.setProperty("DB2_PASSWORD", secret.getPassword());}String mongosecret = getSecretRes(client, SecretConstant.SECRET_MONGO);if(StringUtils.isNotBlank(mongosecret)) {SecretDto secret = JsonUtils.stringToJavaObject(mongosecret, SecretDto.class);System.setProperty("MGDB_URI", "mongodb://"+secret.getUsername()+":"+secret.getPassword()+"@"+ secret.getHost()+":"+secret.getPort()+"/?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");}}private String getSecretRes(SecretsManagerClient client, String secretName) {GetSecretValueRequest request = GetSecretValueRequest.builder().secretId(secretName).build();return client.getSecretValue(request).secretString();}}