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

Spring Cloud Consul

項目是針對Consul的服務治理實現。Consul是一個分佈式高可用的系統,具備分佈式、高可用、高擴展性html

Consul

Consul 是 HashiCorp 公司推出的開源工具,用於實現分佈式系統的服務發現與配置。與其餘分佈式服務註冊與發現的方案,Consul的方案更「一站式」 ,內置了服務註冊與發現框 架、具備如下性質:
● 分佈一致性協議實現
● 健康檢查
● Key/Value存儲
● 多數據中心方案
再也不須要依賴其餘工具(好比ZooKeeper等)git

添加依賴

<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.ymlspring

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模式)bash

-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/ 去訪問 app

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等多種登陸,提供配套視頻開發教程
相關文章
相關標籤/搜索