傳統作法
在之前實現的config-server基礎上來實現高可用非常簡單,不需要我們為這些服務端做任何額外的配置,只需要遵守一個配置規則:將所有的Config Server都指向同一個Git倉庫,這樣所有的配置內容就通過統一的共享文件系統來維護,而客戶端在指定Config Server位置時,只要配置Config Server外的均衡負載即可,就像如下圖所示的結構
注冊為服務
把config-server也注冊為服務,這樣所有客戶端就能以服務的方式進行訪問。通過這種方法,只需要啟動多個指向同一Git倉庫位置的config-server就能實現高可用了。
config-server配置
pom.xml依賴
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>
在application.properties
中配置參數eureka.client.serviceUrl.defaultZone
以指定服務注冊中心的位置
spring.application.name=config-server server.port=7001 # 配置服務注冊中心 eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
# git倉庫配置 spring.cloud.config.server.git.uri=xx spring.cloud.config.server.git.searchPaths=xx spring.cloud.config.server.git.username=username spring.cloud.config.server.git.password=password
應用主類中,新增@EnableDiscoveryClient
注解,用來將config-server注冊到上面配置的服務注冊中心上去。
@EnableDiscoveryClient @EnableConfigServer @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } }
啟動該應用,並訪問http://localhost:1111/
,可以在Eureka Server的信息面板中看到config-server已經被注冊了
config-client配置
pom.xml依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>
在bootstrap.properties
中,按如下配置
spring.application.name=didispace server.port=7002 eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
spring.cloud.config.discovery.enabled=true spring.cloud.config.discovery.serviceId=config-server spring.cloud.config.profile=dev
通過eureka.client.serviceUrl.defaultZone
參數指定服務注冊中心,用於服務的注冊與發現
spring.cloud.config.discovery.enabled
參數設置為true,開啟通過服務來訪問Config Server的功能
spring.cloud.config.discovery.serviceId
參數來指定Config Server注冊的服務名
spring.application.name
和spring.cloud.config.profile
如之前通過URI的方式訪問時候一樣,用來定位Git中的資源。
在應用主類中,增加@EnableDiscoveryClient
注解,用來發現config-server服務,利用其來加載應用配置
@EnableDiscoveryClient @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } }
創建的Controller來加載Git中的配置信息
@RefreshScope @RestController public class TestController { @Value("${from}") private String from; @RequestMapping("/from") public String from() { return this.from; } }
訪問客戶端應用提供的服務:http://localhost:7002/from
,此時,我們會返回在Git倉庫中didispace-dev.properties
文件配置的from屬性內容:”git-dev-1.0”