Spring Cloud Consul入門


1. Consul介紹

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

image

Consul包含多個組件,但是作為一個整體,為你的基礎設施提供服務發現和服務配置的工具.他提供以下關鍵特性:

  • 服務發現
    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%中去。

2.1 驗證安裝

安裝Consul后,通過打開新的終端回話並且輸入consul是否可用來驗證安裝是否工作。通過執行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 開發模式運行:

$ 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。另外,本地的成員已經被標記為一個健康的集群成員。

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

3.2 查看集群成員

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

$ 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 選項來查看。

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端口。

$ 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的各個服務治理框架中。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM