Consul微服務的配置中心體驗篇

gggggwww發表於2018-07-05

Spring Cloud Consul

專案是針對Consul的服務治理實現。Consul是一個分散式高可用的系統,具有分散式、高可用、高擴充套件性

Consul

Consul 是 HashiCorp 公司推出的開源工具,用於實現分散式系統的服務發現與配置。與其他分散式服務註冊與發現的方案,Consul的方案更“一站式” ,內建了服務註冊與發現框 架、具有以下性質:
● 分佈一致性協議實現
● 健康檢查
● Key/Value儲存
● 多資料中心方案
不再需要依賴其他工具(比如ZooKeeper等)

新增依賴

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-consul-all</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
複製程式碼

consul-all依賴提供了哪些功能?

<!--訊息匯流排,提供配置實時重新整理,不再依賴中介軟體-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-consul-bus</artifactId>
</dependency>
<!--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>
複製程式碼

bootstarp.yml

這裡要注意是要配置在 bootstarp.yml

spring:
  application:
    name: pig-consul
  cloud:
    consul:
      host: localhost
      port: 8500
      config:
        enabled: true
        format: KEY_VALUE
        watch:
          enabled: true
        prefix: pig-config
  
複製程式碼

安裝consul

下載: https://www.consul.io/downloads.html
使用:(dev模式,生成建議cluster模式)

-dev表示開發模式執行,使用-client 引數可指定允許客戶端使用什麼ip去訪問,例如-client 127.0.0.1 表示可以使用。  

consul agent -dev -client 127.0.0.1
複製程式碼

生產配置參考:
https://www.consul.io/intro/getting-started/join.html
http://127.0.0.1:8500/ui/ 去訪問

image

配置config

image

demo

@RestController
public class DemoController {
    @Value("${author}")
    private String author;

    @GetMapping("/demo")
    public String demo() {
        return author;
    }
}
複製程式碼

關於實時重新整理配置

spring:
  cloud:
    consul:
      config:
        watch:
          enabled: true
複製程式碼

然後應用要開啟定時任務

@EnableScheduling
複製程式碼

總結

  1. 相較於spring cloud config 的配置中心,使用起來較為麻煩,但是對於實時重新整理,這塊要優於spring cloud config 的,不依賴於中介軟體的訊息通知,也不會出現服務下線的問題。
  2. 這篇文章主要是入門,更高階的使用Consul Config 結合 Git 來做版本控制,請參考我後邊的文章
  3. 關於pig:基於Spring Cloud、oAuth2.0開發基於Vue前後分離的開發平臺,支援賬號、簡訊、SSO等多種登入,提供配套視訊開發教程

相關文章