在前面的部落格中,我們實作了配置檔案統一管理的功能,但是我們可以發現,我們僅僅隻用了一個server,如果當這個server挂掉的話,整個配置中心就會不可用,下面,我們就來解決配置中心的高可用問題。
下面我們通過整合Eureka來實作配置中心的高可用,因為作為架構内的配置管理,本身其實也是可以看作架構中的一個微服務,我們可以把config server也注冊為服務,這樣所有用戶端就能以服務的方式進行通路。通過這種方法,隻需要啟動多個指向同一Gitlab倉庫位置的config server端就能實作高可用了。
一、Config Server端加入Eureka
1、加入Eureka依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
2、添加Eureka支援,将配置服務注冊到Eureka上去
@EnableEurekaClient
3、修改Server端的配置檔案
加入Eureka注冊的配置,bootstrap.yml
server:
port: 8889
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
instance:
prefer-ip-address: true
spring:
application:
name: foo
cloud:
config:
server:
git:
uri: https://gitlab.xxx.com/xxxxx/xxxxx.git # 配置gitlab倉庫的位址
search-paths: /config-repo # gitlab倉庫位址下的相對位址,可以配置多個,用,分割。
username: your name # gitlab倉庫的賬号
password: your password # gitlab倉庫的密碼
啟動Config Server
4、修改端口号,再啟動一個Config Server
5、檢視服務是否注冊成功
二、Config 用戶端加入Eureka
1、加入Eureka的pom依賴,同Config Server
2、修改Config用戶端的配置文
件
bootstrap.properties經過測試,此處用戶端隻能是bootstrap.properties,否則會一直連端口8888
server.port=8890
spring.application.name=configserver
spring.cloud.config.name=configserver
spring.cloud.config.profile=dev
spring.cloud.config.label=master
# 開啟Config服務發現支援
spring.cloud.config.discovery.enabled=true
# 此處需要設定成Config Server在Eureka上注冊的服務名
spring.cloud.config.discovery.service-id=foo
# 指定服務發現中心
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
其中,通過
eureka.client.service-url.defaultZone
參數指定服務注冊中心,用于服務的注冊與發現,再将
spring.cloud.config.discovery.enabled
參數設定為true,開啟通過服務來通路Config Server的功能,最後利用
spring.cloud.config.discovery.serviceId
參數來指定Config Server注冊的服務名。這裡的
spring.application.name
和
spring.cloud.config.profile
和前面部落格中的意義一緻。
3、在Application主類上添加Eureka支援,同Config Server一緻
三、驗證
1、檢視Eureka Server上的服務
2、檢視Config Server是否正常
在浏覽器中分别輸入:http://localhost:8888/configserver/dev/master,http://localhost:8889/configserver/dev/master,看是否有傳回結果如下:
{
"name": "configserver",
"profiles": [
"dev"
],
"label": "master",
"version": "8949024814dcb6d61f97dc49db7e9dadcfc724b1",
"state": null,
"propertySources": [
{
"name": "https://gitlab.xxx.com/xxxxx/xxxxx/project/config-repo/configserver.properties",
"source": {
"name": "chhliuxyh",
"hello": "i'm the king of the world!!!",
"profile": "profile-default"
}
}
]
}
3、檢視用戶端是否正常
在浏覽器中輸入http://localhost:8890/hello,看是否有如下傳回
i'm the king of the world!!!
如果上面幾步正常,則說明是ok的。
4、将8888端口對應的Config Server停掉,然後重新輸入http://localhost:8890/hello,看是否ok!我們發現仍然是ok的,這樣我們就完成了配置中心的高可用了!