前言
重構成微服務后,每個服務都需要部署很多個實例,在修改配置時不可能每個實例手動去修改,因此使用springboot-config。本想使用git,還是由於公司內部問題只能使用svn,記錄下搭建配置中心的過程
創建SVN目錄上傳配置
這步驟就不細說...最終的目錄為http://....../config-repo/trunk/**/**--dev.yml,http://....../config-repo/trunk/**/**--prod.yml
這里的trunk就用於分辨線上和開發的目錄,最后后綴的dev和prod也用於分辨環境(因為svn默認就是trunk,目錄上必須有這一層,實際上這層是沒有必要的)
config-server
配置中心的也是一個服務,pom文件中需要引入
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
application.yml文件如下, 使用svn的話spring.profiles.active: subversion這項必須指定
server:
port: 8888
spring:
application:
name: service-config
profiles:
active: subversion # 使用svn
cloud:
config:
server:
svn:
uri: http://** #svn地址
search-paths: "{application}" #使用{application}占位符 必須加" " 否則 不識別文件夾搜索
username: user
password: pwd
default-label: trunk
eureka:
client:
service-url:
defaultZone: http://0.0.0.0:8761/eureka/
# 允許/actuator/bus-refresh接口被外部調用, 手動刷新config
management:
endpoints:
web:
exposure:
include: "*"
config-server服務的啟動類需要加上@EnableConfigServer注解
到此為止服務端就搭建好了,可以啟動后嘗試訪問http://0.0.0.0:8888/(配置文件名)查看是否可以正常訪問
倉庫中的配置文件會被轉換成web接口,訪問可以參照以下的規則:
- /{application}/{profile}[/{label}]
- /{application}-{profile}.yml
- /{label}/{application}-{profile}.yml
- /{application}-{profile}.properties
- /{label}/{application}-{profile}.properties
以neo-config-dev.properties為例子,它的application是neo-config,profile是dev。client會根據填寫的參數來選擇讀取對應的配置
configserver每次都是從svn的最新版本讀取內容
客戶端(微服務端)
添加依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
每個服務的配置文件都需要名為bootstrap.yml, springboot在啟動時會優先讀取這個名字的配置文件
spring:
application:
name: entry-service
profiles:
active: subversion
cloud:
config:
name: {application}
label: trunk
discovery:
enabled: true
service-id: service-config # 注冊中心的服務名
profile: dev # 指定配置文件的環境
eureka:
client:
serviceUrl:
defaultZone: http://0.0.0.0:8761/eureka/
配置文件如上,需要指定配置中心的id,實際就是config-server的application.name,並且使用svn的話spring.profiles.active: subversion這項也必須指定
配置完成后啟動即可從配置中心讀取,在使用@Value注入配置的類上加上@RefreshScope, 然后訪問/actuator/refresh就可以刷新配置
遇到的兩個問題:
1. 因為項目是多數據源,所以使用的是自定義數據源配置的DataSource,用@Bean注入。
SpringBoot 2.0以上默認使用Hikari連接池,一旦連接池啟動,就無法再修改HikariDataSource,所以刷新配置時連帶數據源一起刷新,於是會報錯。
Caused by: java.lang.IllegalStateException: The configuration of the pool is sealed once started. Use HikariConfigMXBean for runtime changes.
解決方法: 在自定義的DataSource上加入注解@RefreshScope,或者使用spring.scloud.refresh.extra-refreshable配置指定classname列表即可。
2.使用/refresh報404,SpringBoot 2.0以后接口為/actuator/refresh, 且必須為post請求