一、概述
1. 為什么使用?
1> 配置文件太多,不方便維護
2> 配置文件一般都保存這各種明文顯示的密碼,無法保證配置內容的安全性,也無法做到按權限分配給個人
3> 更新配置項目需重啟,試想想,在生產環境,那么多台機器。。。
2. config介紹
config分為Server端和Client端,實現原理如下圖所示:
- Server端負責從遠端git(碼雲、GitHub等)拉取配置,並緩存在本地;
- Client端(上圖的product和order服務)在啟動時,從Server端本地緩存中獲取配置
二、Server端配置
1. 新建config Server模塊,加載依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
2. 在啟動類上@EnableConfigServer注解,開啟configServer
@EnableConfigServer //開啟configServer @SpringBootApplication @EnableDiscoveryClient //開啟Eureka Client public class TestConfigApplication { public static void main(String[] args) { SpringApplication.run(TestConfigApplication.class, args); } }
3. 在遠端git上新建項目(這里使用碼雲),並把配置上傳上去,具體操作略
說明:config語法規定,xxx.yml為公共配置,在拉取配置時會和xxx.{}profiles}.yml合並
4. 修改配置文件
spring: application: name: test-config profiles: active: dev
#配置中心 cloud: config: server: git: uri: https://gitee.com/wslook/test-config-repo.git search-paths: user //配置文件目錄,多個用逗號隔開 username: xxx password: xxx default-label: master basedir: ./configRepo/ //本地緩存地址 force-pull: true //強制拉取配置,解決手動修改本地緩存配置后,無法拉取最新配置的問題
# 注冊中心
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:2181/eureka/
5. 測試
三、Client端配置
1. 加載依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
2. 修改配置文件(把配置文件名改為bootstrap.yml)
spring: # 配置中心 cloud: config: name: user-config profile: dev label: master discovery: enabled: true serviceId: test-config fail-fast: true # 注冊中心 eureka: instance: prefer-ip-address: true client: service-url: defaultZone: http://localhost:2181/eureka/
3. 測試
編寫測試代碼:
@RequestMapping("/test") @RestController public class TestController { @Resource private OSSProperties ossProperties; @RequestMapping("/config") public String test(){ return ossProperties.getUrl(); } }
啟動user服務,可以看到,已經把配置拉取下來了
使用postman驗證
四、高可用
對於config集群,很簡單,因為由注冊中心(這里使用的eureka)統一管理服務,所以不需要額外的配置,只需多啟動幾台config Server服務即可