Spring Cloud Consul入門

導讀:

Consul是一套開源的分布式服務(wù)發(fā)現(xiàn)和配置管理系統(tǒng),支持多數(shù)據(jù)中心分布式高可用。Consul是HashiCorp( Vagrant的創(chuàng)建者)開發(fā)的一個服務(wù)發(fā)現(xiàn)與配置項目,用Go語言開發(fā),基于 Mozilla Public License 2.0 的協(xié)議開源。

Consul

1. 介紹

Consul包含多個組件,作為提供服務(wù)發(fā)現(xiàn)和服務(wù)配置的工具。它提供以下關(guān)鍵特性:

  • 服務(wù)發(fā)現(xiàn)
    Consul的客戶端可用提供一個服務(wù),比如 api 或者mysql ,另外一些客戶端可用使用Consul去發(fā)現(xiàn)一個指定服務(wù)的提供者.通過DNS或者HTTP應用程序可用很容易的找到他所依賴的服務(wù)。
  • 健康檢查
    Consul客戶端可用提供任意數(shù)量的健康檢查,指定一個服務(wù)(比如:webserver是否返回了200 OK 狀態(tài)碼)或者使用本地節(jié)點(比如:內(nèi)存使用是否大于90%). 這個信息可由operator用來監(jiān)視集群的健康.被服務(wù)發(fā)現(xiàn)組件用來避免將流量發(fā)送到不健康的主機。
  • Key/Value存儲
    應用程序可用根據(jù)自己的需要使用Consul的層級的Key/Value存儲.比如動態(tài)配置,功能標記,協(xié)調(diào),領(lǐng)袖選舉等等,簡單的HTTP API讓他更易于使用。
  • 多數(shù)據(jù)中心
    Consul支持開箱即用的多數(shù)據(jù)中心.這意味著用戶不需要擔心需要建立額外的抽象層讓業(yè)務(wù)擴展到多個區(qū)域。

2. 安裝

下載頁面中找到和你系統(tǒng)匹配的包。解壓Consul zip包,復制consul二進制文件到系統(tǒng)PATH中包含的路徑下,以確保它可以被執(zhí)行。在Unix系統(tǒng)中,~/bin和/usr/local/bin是通常的安裝路徑,選擇哪個依賴于你安裝Consul給單個用戶使用還是所有用戶都可以使用。對于Windows系統(tǒng),可以安裝到任意目錄,記得將安裝目錄添加到%PATH%中。

2.1 驗證安裝

安裝Consul后,通過打開新的終端回話并且輸入consul是否可用來驗證安裝是否工作。通過執(zhí)行consul你應該可以看到下面類似的輸出:

$ 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 開發(fā)模式運行:

$ 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代理已經(jīng)啟動并且輸出了一些日志信息。從日志信息中,你可以看到我們代理運行在服務(wù)器模式并且聲明集群的leadship。另外,本地的成員已經(jīng)被標記為一個健康的集群成員。

OS X用戶注意:Consul使用你的機器名作為默認的節(jié)點名稱。如果你的機器名包涵了點,那么DNS查詢該節(jié)點會不能工作,為了避免這個問題,使用-node顯式設(shè)置你的節(jié)點名稱。

3.2 查看集群成員

如果你在另一個終端中運行 consul members ,你能看到Consul集群所有的節(jié)點,但是現(xiàn)在你只能看到一個成員(你自己的機器)

$ 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>

該命令輸出顯示你自己的節(jié)點,運行的地址,它的健康狀態(tài),它在集群中的角色,以及一些版本信息。另外元數(shù)據(jù)可以通過 -detailed 選項來查看。

members 命令選項的輸出是基于 gossip協(xié)議 的并且其內(nèi)容是最終一致。也就是說,在任何時候,你在本地代理看到的內(nèi)容也許與當前服務(wù)器中的狀態(tài)并不是絕對一致的。如果需要強一致性的狀態(tài)信息,使用HTTP API向Consul服務(wù)器發(fā)送請求:

$ 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接口也常被用來查詢節(jié)點信息。注意你必須確信你的DNS能夠找到Consul代理的DNS服務(wù)器,Consul代理的DNS服務(wù)器默認運行在8600端口。

$ 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組件

下面我們創(chuàng)建提供服務(wù)的客戶端,并向Consul服務(wù)注冊中心注冊自己。
首先,使用IDEA創(chuàng)建一個Spring Initializr創(chuàng)建一個基本的Spring Boot應用并選擇Consul Dependencies:

Add dependencies

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的配置除了可以使用傳統(tǒng)的propertiese文件外,還支持現(xiàn)在被廣泛推薦使用的YAML文件。YAML文件使用類似大綱的縮進形式進行表示,結(jié)構(gòu)更加清晰易讀。

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

啟動工程后,訪問:http://localhost:8500/ui/#/dc1/services,
可以看到下面的頁面,已經(jīng)成功注冊了服務(wù)。

Consul view

服務(wù)發(fā)現(xiàn)的接口DiscoveryClient是Spring Cloud對服務(wù)治理做的一層抽象,所以可以屏蔽Eureka和Consul服務(wù)治理的實現(xiàn)細節(jié),我們的程序不需要做任何改變,只需要引入不同的服務(wù)治理依賴,并配置相關(guān)的配置屬性就能輕松的將微服務(wù)納入Spring Cloud的各個服務(wù)治理框架中。

本來想接著寫consul配合docker搭建高可用集群的,放下期吧…古耐~?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容