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

Spring Cloud Consul 項目是針對Consul的服務治理實現。Consul是一個分佈式高可用的系統,具備分佈式、高可用、高擴展性。html

Consul 簡介

Consul 是 HashiCorp 公司推出的開源工具,用於實現分佈式系統的服務發現與配置。與其餘分佈式服務註冊與發現的方案,Consul的方案更「一站式」 ,內置了服務註冊與發現框 架、具備如下性質:java

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

再也不須要依賴其餘工具(好比ZooKeeper等)。node

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

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 無此功能.nginx

Consul 的角色

client: 客戶端, 無狀態, 將 HTTP 和 DNS 接口請求轉發給局域網內的服務端集羣.server: 服務端, 保存配置信息, 高可用集羣, 在局域網內與本地客戶端通信, 經過廣域網與其餘數據中心通信. 每一個數據中心的 server 數量推薦爲 3 個或是 5 個.git

因爲Spring Cloud Consul項目的實現,咱們能夠輕鬆的將基於Spring Boot的微服務應用註冊到Consul上,並經過此實現微服務架構中的服務治理。github

搭建環境

參考web

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

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

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:關注公衆號,搜雲庫,專一於開發技術的研究與知識分享

關注公衆號-搜雲庫
搜雲庫
相關文章
相關標籤/搜索