Spring Cloud(二) Consul 服務治理實現

搜雲庫技術團隊發表於2017-12-01

Spring Cloud Consul 專案是針對Consul的服務治理實現。Consul是一個分散式高可用的系統,具有分散式、高可用、高擴充套件性。

Consul 簡介

Consul 是 HashiCorp 公司推出的開源工具,用於實現分散式系統的服務發現與配置。與其他分散式服務註冊與發現的方案,Consul的方案更“一站式” ,內建了服務註冊與發現框 架、具有以下性質:

  • 分佈一致性協議實現、
  • 健康檢查、
  • Key/Value儲存、
  • 多資料中心方案,

不再需要依賴其他工具(比如ZooKeeper等)。

使用起來也較 為簡單。Consul使用Go語言編寫,因此具有天然可移植性(支援Linux、windows和Mac OS X);安裝包僅包含一個可執行檔案,方便部署,與Docker等輕量級容器可無縫配合 。 基於 Mozilla Public License 2.0 的協議進行開源. Consul 支援健康檢查,並允許 HTTP 和 DNS 協議呼叫 API 儲存鍵值對. 一致性協議採用 Raft 演算法,用來保證服務的高可用. 使用 GOSSIP 協議管理成員和廣播訊息, 並且支援 ACL 訪問控制.

Consul 的使用場景

  • docker 例項的註冊與配置共享
  • coreos 例項的註冊與配置共享
  • vitess 叢集
  • SaaS 應用的配置共享
  • 與 confd 服務整合,動態生成 nginx 和 haproxy 配置檔案

Consul 的優勢

使用 Raft 演算法來保證一致性, 比複雜的 Paxos 演算法更直接. 相比較而言, zookeeper 採用的是 Paxos, 而 etcd 使用的則是 Raft. 支援多資料中心,內外網的服務採用不同的埠進行監聽。 多資料中心叢集可以避免單資料中心的單點故障,而其部署則需要考慮網路延遲, 分片等情況等. zookeeper 和 etcd 均不提供多資料中心功能的支援. 支援健康檢查. etcd 不提供此功能. 支援 http 和 dns 協議介面. zookeeper 的整合較為複雜, etcd 只支援 http 協議. 官方提供web管理介面, etcd 無此功能.

Consul 的角色

client: 客戶端, 無狀態, 將 HTTP 和 DNS 介面請求轉發給區域網內的服務端叢集.server: 服務端, 儲存配置資訊, 高可用叢集, 在區域網內與本地客戶端通訊, 通過廣域網與其他資料中心通訊. 每個資料中心的 server 數量推薦為 3 個或是 5 個.

由於Spring Cloud Consul專案的實現,我們可以輕鬆的將基於Spring Boot的微服務應用註冊到Consul上,並通過此實現微服務架構中的服務治理。

搭建環境

參考

要想利用Consul提供的服務實現服務的註冊與發現,我們需要搭建Consul Cluster 環境。

在Consul方案中,每個提供服務的節點上都要部署和執行Consul的agent,所有執行Consul agent節點的集合構成Consul Cluster。

Consul agent有兩種執行模式:Server和Client。這裡的Server和Client只是Consul叢集層面的區分,與搭建在Cluster之上 的應用服務無關。

以Server模式執行的Consul agent節點用於維護Consul叢集的狀態,官方建議每個Consul Cluster至少有3個或以上的執行在Server mode的Agent,Client節點不限。

環境配置如下:

Centos 7.3

主機名稱 IP 作用 是否允許遠端訪問
node1 192.168.252.121 consul server
node2 192.168.252.122 consul client
node3 192.168.252.123 consul client

關閉防火牆

systemctl stop firewalld.service
複製程式碼

Consul 最新版的下載地址:
releases.hashicorp.com/consul/1.0.…

下載,然後unzip 解壓,得到唯一,一個可執行檔案

cd /opt/
wget https://releases.hashicorp.com/consul/1.0.1/consul_1.0.1_linux_amd64.zip
unzip consul_1.0.1_linux_amd64.zip
cp consul /usr/local/bin/
複製程式碼

檢視是否安裝成功

[root@node1 opt]# 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
複製程式碼

檢查版本

[root@node1 opt]# consul version
複製程式碼
Consul v1.0.1
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)
複製程式碼

Consul常用命令

命令 解釋 示例
agent 執行一個consul agent consul agent -dev
join 將agent加入到consul叢集 consul join IP
members 列出consul cluster叢集中的members consul members
leave 將節點移除所在叢集 consul leave

consul agent 命令的常用選項

-data-dir

  • 作用:指定agent儲存狀態的資料目錄
  • 這是所有agent都必須的
  • 對於server尤其重要,因為他們必須持久化叢集的狀態

-config-dir

  • 作用:指定service的配置檔案和檢查定義所在的位置
  • 通常會指定為”某一個路徑/consul.d”(通常情況下,.d表示一系列配置檔案存放的目錄)

-config-file

  • 作用:指定一個要裝載的配置檔案
  • 該選項可以配置多次,進而配置多個配置檔案(後邊的會合並前邊的,相同的值覆蓋)

-dev

  • 作用:建立一個開發環境下的server節點
  • 該引數配置下,不會有任何持久化操作,即不會有任何資料寫入到磁碟
  • 這種模式不能用於生產環境(因為第二條)

-bootstrap-expect

  • 作用:該命令通知consul server我們現在準備加入的server節點個數,該引數是為了延遲日誌複製的啟動直到我們指定數量的server節點成功的加入後啟動。

-node

  • 作用:指定節點在叢集中的名稱
  • 該名稱在叢集中必須是唯一的(預設採用機器的host)
  • 推薦:直接採用機器的IP

-bind

  • 作用:指明節點的IP地址
  • 有時候不指定繫結IP,會報Failed to get advertise address: Multiple private IPs found. Please configure one. 的異常

-server

  • 作用:指定節點為server
  • 每個資料中心(DC)的server數推薦至少為1,至多為5
  • 所有的server都採用raft一致性演算法來確保事務的一致性和線性化,事務修改了叢集的狀態,且叢集的狀態儲存在每一臺server上保證可用性
  • server也是與其他DC互動的門面(gateway)

-client

  • 作用:指定節點為client,指定客戶端介面的繫結地址,包括:HTTP、DNS、RPC
  • 預設是127.0.0.1,只允許迴環介面訪問
  • 若不指定為-server,其實就是-client

-join

  • 作用:將節點加入到叢集

-datacenter(老版本叫-dc,-dc已經失效)

  • 作用:指定機器加入到哪一個資料中心中

啟動服務

我們嘗試一下:

-dev表示開發模式執行,使用-client 引數可指定允許客戶端使用什麼ip去訪問,例如-client 192.168.252.121 表示可以使用

http://192.168.252.121:8500/ui/ 去訪問。

consul agent -dev -client 192.168.252.121
複製程式碼

Consul Cluster

Consul 的高可用

Consul Cluster叢集架構圖如下:

Consul Cluster叢集架構

這邊準備了三臺Centos 7.3的虛擬機器,主機規劃如下,供參考:

主機名稱 IP 作用 是否允許遠端訪問
node1 192.168.252.121 consul server
node2 192.168.252.122 consul client
node3 192.168.252.123 consul client

搭建步驟

命令引數,參看上面詳細介紹

在 node1 機器上啟動 Consul

cd /opt/
mkdir data
consul agent -data-dir /opt/data -node=192.168.252.121 -bind=0.0.0.0 -datacenter=dc1 -ui -client=192.168.252.121 -server -bootstrap-expect 1 > /dev/null 2>&1 &
複製程式碼

在 node2 機器上啟動 Consul,並且將node2節點加入到node1節點上

cd /opt/
mkdir data
consul agent -data-dir /opt/data -node=192.168.252.122 -bind=0.0.0.0 -datacenter=dc1 -ui -client=192.168.252.122 -join=192.168.252.121 > /dev/null 2>&1 &
複製程式碼

在 node3 機器上啟動 Consul,並且將node3節點加入到node1節點上

cd /opt/
mkdir data
consul agent -data-dir /opt/data -node=192.168.252.123 -bind=0.0.0.0 -datacenter=dc1 -ui  -client=192.168.252.123 -join=192.168.252.121 > /dev/null 2>&1 &
複製程式碼

在node1上檢視當前叢集節點:

consul members -rpc-addr=192.168.252.123:8400  

consul leave -rpc-addr=192.168.252.123:8400  

複製程式碼

http://192.168.252.121:8500/ui/ 去訪問。

Consul Cluster叢集 nodes

專案示例

新建專案:spring-cloud-consul-client

新增依賴

在專案 spring-cloud-consul-client pom.xml中引入需要的依賴內容:

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
複製程式碼

開啟服務註冊

客戶端註冊Consul時,它提供有關自身的後設資料,如主機和埠,ID,名稱和標籤。預設情況下,將建立一個HTTP 檢查,每隔10秒Consul命中/health端點。如果健康檢查失敗,則服務例項被標記為關鍵。

package io.ymq.example.consul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ConsulApplication {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

	public static void main(String[] args) {
		SpringApplication.run(ConsulApplication.class, args);
	}
}
複製程式碼

配置檔案

application.yml配置檔案中增加如下資訊:如果Consul客戶端位於localhost:8500以外,則需要配置來定位客戶端

spring:
  application:
    name: consul-client
  cloud:
    consul:
      host: 192.168.252.121
      port: 8500
      discovery:
        healthCheckPath: /
        healthCheckInterval: 5s
複製程式碼

如果Consul客戶端位於localhost:8500以外的位置,則需要配置來定位客戶端。例:

host: 192.168.252.121
port: 8500
複製程式碼

HTTP健康檢查路徑 INSTALL

“10s”和“1m”分別表示10秒和1分

discovery:
	healthCheckPath: ${management.context-path}/health
	healthCheckInterval: 15s
複製程式碼

啟動服務

spring-cloud-consul-client 專案根目錄下,執行mvn clean package,把target 目錄下 生成的 jar spring-cloud-consul-client-0.0.1-SNAPSHOT.jar 上傳伺服器,釋出專案

打包命令

mvn clean package
複製程式碼

釋出命令

nohup java -jar spring-cloud-consul-client-0.0.1-SNAPSHOT.jar  > /dev/null 2>&1 &
複製程式碼

訪問服務

http://192.168.252.121:8500/ui/#/dc1/nodes/192.168.252.121

Consul Cluster 叢集 服務註冊情況

Consul Cluster叢集 服務註冊情況

Consul Cluster叢集 服務註冊情況

通過上圖HTTP健康檢查,可以看到服務檢測正常

原始碼下載

GitHub:github.com/souyunku/sp…

碼雲:gitee.com/souyunku/sp…

Contact

  • 作者:鵬磊
  • 出處:www.ymq.io
  • Email:admin@souyunku.com
  • 版權歸作者所有,轉載請註明出處
  • Wechat:關注公眾號,搜雲庫,專注於開發技術的研究與知識分享

關注公眾號-搜雲庫
搜雲庫

相關文章