SpringBoot實戰電商項目mall(20k+star)地址:github.com/macrozheng/…html
Spring Cloud Consul 爲 SpringBoot 應用提供了 Consul的支持,Consul既能夠做爲註冊中心使用,也能夠做爲配置中心使用,本文將對其用法進行詳細介紹。java
Consul是HashiCorp公司推出的開源軟件,提供了微服務系統中的服務治理、配置中心、控制總線等功能。這些功能中的每個均可以根據須要單獨使用,也能夠一塊兒使用以構建全方位的服務網格,總之Consul提供了一種完整的服務網格解決方案。git
Spring Cloud Consul 具備以下特性:github
下載完成後只有一個exe文件,雙擊運行;spring
在命令行中輸入如下命令能夠查看版本號:shell
consul --version
複製代碼
Consul v1.6.1
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)
複製代碼
consul agent -dev
複製代碼
咱們經過改造user-service和ribbon-service來演示下服務註冊與發現的功能,主要是將應用原來的Eureka註冊中心支持改成Consul註冊中心支持。bootstrap
建立consul-user-service模塊和consul-ribbon-service模塊;bash
修改相關依賴,把原來的Eureka註冊發現的依賴改成Consul的,並添加SpringBoot Actuator的依賴:app
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
複製代碼
server:
port: 8206
spring:
application:
name: consul-user-service
cloud:
consul: #Consul服務註冊發現配置
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
複製代碼
因爲咱們運行了兩個consul-user-service,而consul-ribbon-service默認會去調用它的接口,咱們調用consul-ribbon-service的接口來演示下負載均衡功能。負載均衡
屢次調用接口:http://localhost:8308/user/1 ,能夠發現兩個consul-user-service的控制檯交替打印以下信息。
2019-10-20 10:39:32.580 INFO 12428 --- [io-8206-exec-10] c.macro.cloud.controller.UserController : 根據id獲取用戶信息,用戶名稱爲:macro
複製代碼
咱們經過建立consul-config-client模塊,並在Consul中添加配置信息來演示下配置管理的功能。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
複製代碼
spring:
profiles:
active: dev
複製代碼
server:
port: 9101
spring:
application:
name: consul-config-client
cloud:
consul:
host: localhost
port: 8500
discovery:
serviceName: consul-config-client
config:
enabled: true #是否啓用配置中心功能
format: yaml #設置配置值的格式
prefix: config #設置配置所在目錄
profile-separator: ':' #設置配置的分隔符
data-key: data #配置key的名字,因爲Consul是K/V存儲,配置存儲在對應K的V中
複製代碼
/** * Created by macro on 2019/9/11. */
@RestController
@RefreshScope
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/configInfo")
public String getConfigInfo() {
return configInfo;
}
}
複製代碼
config/consul-config-client:dev/data
複製代碼
config:
info: "config info for dev"
複製代碼
config info for dev
複製代碼
咱們只要修改下Consul中的配置信息,再次調用查看配置的接口,就會發現配置已經刷新。回想下在使用Spring Cloud Config的時候,咱們須要調用接口,經過Spring Cloud Bus才能刷新配置。Consul使用其自帶的Control Bus 實現了一種事件傳遞機制,從而實現了動態刷新功能。
springcloud-learning
├── consul-config-client -- 用於演示consul做爲配置中心的consul客戶端
├── consul-user-service -- 註冊到consul的提供User對象CRUD接口的服務
└── consul-service -- 註冊到consul的ribbon服務調用測試服務
複製代碼
mall項目全套學習教程連載中,關注公衆號第一時間獲取。