Spring Cloud Consul入門(mén)

導(dǎo)讀:

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

Consul

1. 介紹

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

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

2. 安裝

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

2.1 驗(yàn)證安裝

安裝Consul后,通過(guò)打開(kāi)新的終端回話(huà)并且輸入consul是否可用來(lái)驗(yàn)證安裝是否工作。通過(guò)執(zhí)行consul你應(yīng)該可以看到下面類(lèi)似的輸出:

$ 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. 啟動(dòng)Consul

3.1 開(kāi)發(fā)模式運(yùn)行:

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

OS X用戶(hù)注意:Consul使用你的機(jī)器名作為默認(rèn)的節(jié)點(diǎn)名稱(chēng)。如果你的機(jī)器名包涵了點(diǎn),那么DNS查詢(xún)?cè)摴?jié)點(diǎn)會(huì)不能工作,為了避免這個(gè)問(wèn)題,使用-node顯式設(shè)置你的節(jié)點(diǎn)名稱(chēng)。

3.2 查看集群成員

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

$ 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é)點(diǎn),運(yùn)行的地址,它的健康狀態(tài),它在集群中的角色,以及一些版本信息。另外元數(shù)據(jù)可以通過(guò) -detailed 選項(xiàng)來(lái)查看。

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

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

另外對(duì)于HTTP API,DNS接口也常被用來(lái)查詢(xún)節(jié)點(diǎn)信息。注意你必須確信你的DNS能夠找到Consul代理的DNS服務(wù)器,Consul代理的DNS服務(wù)器默認(rèn)運(yùn)行在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ù)的客戶(hù)端,并向Consul服務(wù)注冊(cè)中心注冊(cè)自己。
首先,使用IDEA創(chuàng)建一個(gè)Spring Initializr創(chuàng)建一個(gè)基本的Spring Boot應(yīng)用并選擇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,不添加會(huì)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>

在應(yīng)用主類(lèi)中通過(guò)加上@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文件使用類(lèi)似大綱的縮進(jìn)形式進(jìn)行表示,結(jié)構(gòu)更加清晰易讀。

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

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

Consul view

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

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

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

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