在开发微服务时,往往需要有开发环境、测试环境和生产环境,手动修改配置环境是一件很麻烦的事情,因此,这里使用spring cloud config管理配置环境。要使用spring cloud config,需要先在GitHub搭建一个仓库。
一、仓库搭建
- 创建访问令牌:
仓库搭建成功后,点击右上角头像 → Settings → 左侧导航栏 → Developer settings → Personal access tokens → Tokens (classic) → Generate new token → Generate new token (classic),会生成一个"ghp_"开头的个人访问令牌。该令牌只会出现一次,需要尽快复制保存。之后会在配置文件里使用该令牌。 - 配置仓库文件
在仓库界面点击“Add file—>Create new file”添加文件,如果要创建文件夹,在文件名后面加上“/”即可,如图:
文件名称的格式为“spring.application.name的名称-profile”,例如,假如name是abc,profile是dev,则文件名称是abc-dev.yml
二、服务创建
spring cloud config是一个独立的微服务,该业务功能需要在主启动类的上面添加@EnableConfigServer。此外,还需要在pom.xml添加以下依赖文件:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
添加完成后,在application.yaml里添加以下配置:
server:
port: 8888
spring:
application:
name: configServer
cloud:
config:
server:
git:
uri: https://github.com/xxx.git
username: GitHub用户
password: ghp_开头的令牌
default-label: main /默认在哪个分支进行配置搜索
search-paths:
- userClient #GitHub仓库里的文件夹
- gateway
clone-on-start: true
profiles:
active:
- dev
三、启用对应配置
配置完成后,在需要进行环境管理的微服务application.yaml里添加以下配置:
spring:
config:
import: "configserver:http://localhost:8888" # 指向 Config Server 地址
application:
name: userClient # 客户端应用名(对应 Config Server 中的 {application})
profiles:
active: dev # 环境(对应 Config Server 中的 {profile})
management:
endpoints:
web:
exposure:
include: refresh
这里我使用的是在文件夹userClient下面的userClient-dev.yml配置文件,所以name为userClient,active写dev,如图:
四、测试
配置完成后,可以在浏览器访问 localhost:8888/应用名称/{profile}/分支进行测试。例如,我要测试userClient-dev.yml是否有正确配置,可以访问 localhost:8888/userclient/dev/main,正常情况下有如下json数据结构显示:
{
"name": "userClient",
"profiles": [
"dev"
],
"label": "main",
"version": "28ce72e805936d22c73fc61091b51b85bf8ec5b0",
"state": "",
"propertySources": [
{
"name": "https://github.com/xxx.git/userClient/userClient-dev.yml",
"source": {
"server.port": 8120,
"spring.application.name": "userClient",
"spring.lifecycle.timeout-per-shutdown-phase": "30s",
"spring.datasource.url": "jdbc:mysql://localhost:3306/personal_management_system?useSSL=false&serverTimezone=UTC&characterEncoding=utf8",
"spring.datasource.username": "name",
"spring.datasource.password": "abcdefg",
"spring.datasource.driver-class-name": "com.mysql.cj.jdbc.Driver",
"spring.jpa.hibernate.ddl-auto": "update",
"spring.jpa.show-sql": true,
"spring.devtools.restart.enabled": true,
"spring.devtools.restart.additional-paths": "src/main",
"spring.devtools.restart.exclude": "WEB-INF/**",
"spring.freemarker.cache": false,
"eureka.client.serviceUrl.defaultZone": "http://localhost:8761/eureka",
"eureka.instance.instance-id": "userClient-service",
"eureka.instance.prefer-ip-address": true
}
}
]
}
该结构显示的是该yml文件的相关配置内容。