Spring Cloud Consul入門

1. Consul介紹

Consul是一套開源的分佈式服務發現和配置管理系統,支持多數據中心分佈式高可用。Consul是HashiCorp( Vagrant的建立者)開發的一個服務發現與配置項目,用Go語言開發,基於 Mozilla Public License 2.0 的協議開源。html

image

Consul包含多個組件,可是做爲一個總體,爲你的基礎設施提供服務發現和服務配置的工具.他提供如下關鍵特性:java

  • 服務發現
    Consul的客戶端可用提供一個服務,好比 api 或者mysql ,另一些客戶端可用使用Consul去發現一個指定服務的提供者.經過DNS或者HTTP應用程序可用很容易的找到他所依賴的服務。
  • 健康檢查
    Consul客戶端可用提供任意數量的健康檢查,指定一個服務(好比:webserver是否返回了200 OK 狀態碼)或者使用本地節點(好比:內存使用是否大於90%). 這個信息可由operator用來監視集羣的健康.被服務發現組件用來避免將流量發送到不健康的主機。
  • Key/Value存儲
    應用程序可用根據本身的須要使用Consul的層級的Key/Value存儲.好比動態配置,功能標記,協調,領袖選舉等等,簡單的HTTP API讓他更易於使用。
  • 多數據中心
    Consul支持開箱即用的多數據中心.這意味着用戶不須要擔憂須要創建額外的抽象層讓業務擴展到多個區域。

2. 安裝

下載頁面中找到和你係統匹配的包。解壓Consul zip包,複製consul二進制文件到系統PATH中包含的路徑下,以確保它能夠被執行。在Unix系統中,~/bin和/usr/local/bin是一般的安裝路徑,選擇哪一個依賴於你安裝Consul給單個用戶使用仍是全部用戶均可以使用。對於Windows系統,你能夠安裝到任意目錄,不過不要忘記將安裝目錄加入到%PATH%中去。node

2.1 驗證安裝

安裝Consul後,經過打開新的終端回話而且輸入consul是否可用來驗證安裝是否工做。經過執行consul你應該能夠看到下面相似的輸出:mysql

$ consul
Usage: consul [--version] [--help] <command> [<args>]

Available commands are:
    agent          Runs a Consul agent
    catalog        Interact with the catalog
    event          Fire a new event
    exec           Executes a command on Consul nodes
    force-leave    Forces a member of the cluster to enter the "left" state
    info           Provides debugging information for operators.
    join           Tell Consul agent to join cluster
    keygen         Generates a new encryption key
    keyring        Manages gossip layer encryption keys
    kv             Interact with the key-value store
    leave          Gracefully leaves the Consul cluster and shuts down
    lock           Execute a command holding a lock
    maint          Controls node or service maintenance mode
    members        Lists the members of a Consul cluster
    monitor        Stream logs from a Consul agent
    operator       Provides cluster-level tools for Consul operators
    reload         Triggers the agent to reload configuration files
    rtt            Estimates network round trip time between nodes
    snapshot       Saves, restores and inspects snapshots of Consul server state
    validate       Validate config files/directories
    version        Prints the Consul version
    watch          Watch for changes in Consul

3. 啓動Consul

3.1 開發模式運行:

$ consul agent -dev
==> Starting Consul agent...
==> Consul agent running!
           Version: 'v1.0.2'
           Node ID: '5231963e-3453-ac4c-cf31-d13736402df9'
         Node name: 'MantouMBP.local'
        Datacenter: 'dc1' (Segment: '<all>')
            Server: true (Bootstrap: false)
       Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, DNS: 8600)
      Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
           Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false

你能夠看到,Consul代理已經啓動而且輸出了一些日誌信息。從日誌信息中,你能夠看到咱們代理運行在服務器模式而且聲明集羣的leadship。另外,本地的成員已經被標記爲一個健康的集羣成員。web

OS X用戶注意:Consul使用你的機器名做爲默認的節點名稱。若是你的機器名包涵了點,那麼DNS查詢該節點會不能工做,爲了不這個問題,使用-node顯式設置你的節點名稱。spring

3.2 查看集羣成員

若是你在另外一個終端中運行 consul members ,你能看到Consul集羣全部的節點,可是如今你只能看到一個成員(你本身的機器)sql

$ consul members
Node             Address         Status  Type    Build  Protocol  DC   Segment
MantouMBP.local  127.0.0.1:8301  alive   server  1.0.2  2         dc1  <all>

該命令輸出顯示你本身的節點,運行的地址,它的健康狀態,它在集羣中的角色,以及一些版本信息。另外元數據能夠經過 -detailed 選項來查看。api

members 命令選項的輸出是基於 gossip協議 的而且其內容是最終一致。也就是說,在任什麼時候候,你在本地代理看到的內容也許與當前服務器中的狀態並非絕對一致的。若是須要強一致性的狀態信息,使用HTTP API向Consul服務器發送請求:服務器

$ curl localhost:8500/v1/catalog/nodes
[
    {
        "ID": "bce12243-d825-ea69-2066-c3e3daae13fb",
        "Node": "MantouMBP.local",
        "Address": "127.0.0.1",
        "Datacenter": "dc1",
        "TaggedAddresses": {
            "lan": "127.0.0.1",
            "wan": "127.0.0.1"
        },
        "Meta": {
            "consul-network-segment": ""
        },
        "CreateIndex": 5,
        "ModifyIndex": 6
    }
]

另外對於HTTP API,DNS接口也常被用來查詢節點信息。注意你必須確信你的DNS可以找到Consul代理的DNS服務器,Consul代理的DNS服務器默認運行在8600端口。app

$ dig @127.0.0.1 -p 8600 MantouMBP.local.node.consul

; <<>> DiG 9.8.3-P1 <<>> @127.0.0.1 -p 8600 MantouMBP.local.node.consul
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 29410
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;MantouMBP.local.node.consul.   IN  A

;; ANSWER SECTION:
MantouMBP.local.node.consul. 0  IN  A   127.0.0.1

;; Query time: 3 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: Thu Dec 28 22:24:05 2017
;; MSG SIZE  rcvd: 61

4. 使用SpringCloud Consul組件

下面咱們建立提供服務的客戶端,並向Consul服務註冊中心註冊本身。
首先,使用IDEA建立一個Spring Initializr建立一個基本的Spring Boot應用並選擇Consul Dependencies:

image

pom.xml中,配置以下:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--consul中健康檢查須要用到actuator,不添加會check failing-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

在應用主類中經過加上@EnableDiscoveryClient註解:

@EnableDiscoveryClient
@SpringBootApplication
public class ClientServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ClientServiceApplication.class, args);
    }
}

配置application.properties:

Spring Boot的配置除了能夠使用傳統的propertiese文件外,還支持如今被普遍推薦使用的YAML文件。YAML文件使用相似大綱的縮進形式進行表示,結構更加清晰易讀。

spring.application.name=client-service
server.port=2001
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500

啓動工程後,訪問:http://localhost:8500/ui/#/dc1/services,
能夠看到下面的頁面,已經成功註冊了服務。

image

服務發現的接口DiscoveryClient是Spring Cloud對服務治理作的一層抽象,因此能夠屏蔽Eureka和Consul服務治理的實現細節,咱們的程序不須要作任何改變,只須要引入不一樣的服務治理依賴,並配置相關的配置屬性就能輕鬆的將微服務歸入Spring Cloud的各個服務治理框架中。

相關文章
相關標籤/搜索