问题
现在手上有一个老Spring2.5.15项目,需要使用AWS Parameter Store作为配置中心服务。
思路
引入这个Spring版本对应的Spring Cloud,然后再引入Spring Cloud AWS相关组件。然后,在AWS云上面准备好配置,然后,启动我本地Spring工程,验证有没有使用云端配置。
Spring Cloud引入

从Spring官网可知,我这个老版本的Spring2.5.15,只能选择Spring Cloud 2020.0.x的Cloud版本。具体依赖如下:
xml
<properties>
<spring-cloud.version>2020.0.6</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
等待一段时间后,然后在引入Spring Cloud AWS集成依赖。
Spring Cloud AWS 依赖引入
xml
<properties>
<spring-cloud-aws.version>2.3.5</spring-cloud-aws.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws-parameter-store-config</artifactId>
<version>${spring-cloud-aws.version}</version>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws-secrets-manager-config</artifactId>
<version>${spring-cloud-aws.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
注意这里也有版本对应要求的,可以查看Spring Cloud AWS在github上面的开源项目介绍,具体如下图:
xml
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws-parameter-store-config</artifactId>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws-secrets-manager-config</artifactId>
</dependency>
Parameter Store创建参数

这里以jdbc连接参数为例子。创建了一个连接参数。
Secrets Manager创建参数
下面设置数据库中用户名和密码,如下图:
配置密钥,如下图:
Spring配置
yaml
spring:
application:
name: api
config:
import:
- aws-parameterstore:/config/${spring.application.name}_${spring.profiles.active}
- aws-secretsmanager:/secret/${spring.application.name}_${spring.profiles.active}
aws:
paramstore:
region: cn-north-1
defaultContext: ${spring.application.name}
secretsmanager:
region: cn-north-1
defaultContext: ${spring.application.name}
注意,这里用到了spring.config.import,这种方式Spring配置是对原来的boot环境多配置文件的替代。
配置调试日志
yaml
# 日志配置
logging:
level:
io:
awspring:
cloud:
paramstore:
AwsParamStorePropertySource: debug
测试验证
重启Spring工程,出现如下内容,说明spring读到了配置:
bash
11:02:13.555 [restartedMain] INFO i.a.c.s.AwsSecretsManagerPropertySources - [logTo,255] - Loading secrets from AWS Secret Manager secret with name: /secret/api_local, optional: false
11:02:13.555 [restartedMain] INFO i.a.c.p.AwsParamStorePropertySources - [logTo,255] - Loading property from AWS Parameter Store with name: /config/api_local, optional: false
11:02:13.555 [restartedMain] DEBUG i.a.c.p.AwsParamStorePropertySource - [logTo,252] - Populating property retrieved from AWS Parameter Store: .spring.datasource.druid.master.url
类似如下效果:
总结
spring.config.import
方式配置,是Spring为了支持云原生配置中心,后面加入新的配置方式,是对boot配置方式的替代。之前写过一篇文章(《Spring Cloud AWS配置中心使用》)就是使用Spring老的boot方式进行的配置。