1. 程式人生 > >SpringCloud——服務註冊(consul)

SpringCloud——服務註冊(consul)

一、consul 簡介

          Consul通過HTTP APIDNS提供服務發現服務。Spring Cloud Consul利用HTTP API進行服務註冊和發現。這不會阻止非Spring Cloud應用程式利用DNS介面。Consul代理伺服器在通過八卦協議進行通訊叢集中執行,並使用Raft協議協議

1、功能

  • 服務發現:Consul client 可以提供服務,例如api或mysql,也可以使用Consul client來發現指定服務的提供者。 使用DNS或HTTP,應用程式可以輕鬆找到他們所依賴的服務。
  • 健康檢查:Consul client 可以提供任何數量的健康檢查,或者與給定的服務(“Web伺服器是否返回200 OK”),或與本地節點(“記憶體利用率是否低於90%”)相關聯。 可以使用此資訊來監控叢集執行狀況,服務發現元件使用此資訊將流量從有問題的主機中移除出去。
  • KV Store:應用程式可以使用Consul的分層鍵/值儲存,包括動態配置,功能標記,協調,leader選舉等等。 簡單的HTTP API使其易於使用。
  • 多資料中心:Consul支援多個數據中心。 這意味著Consul的使用者不必擔心構建額外的抽象層以擴充套件到多個區域。

2、基本架構

    Consul 是一個分散式,高可用的系統。 向Consul提供服務的每個節點都執行一個Consul代理。 發現其他服務或獲取/設定鍵/值資料不需要執行代理。 代理負責健康檢查節點上的服務以及節點本身。代理與一個或多個Consul伺服器通訊。Consul 伺服器是資料儲存和複製的地方。 伺服器自己選出一個 leader。 雖然Consul可以在一臺伺服器上執行,但推薦使用3到5臺來避免資料丟失的情況。 每個資料中心都建議使用一組Consul伺服器。需要發現其他服務或節點的基礎架構元件可以查詢任何Consul伺服器或任何Consul代理。 代理自動將查詢轉發到伺服器。每個資料中心都執行Consul伺服器叢集。 當跨資料中心服務發現或配置請求時,本地Consul伺服器將請求轉發到遠端資料中心並返回結果。

3、安裝(Centos7

解壓:

unzip consul_1.2.3_linux_amd64.zip

就會在當前目下看到consul檔案

inflating: consul                  
[[email protected] soft]# ll
total 44540
-rwxr-xr-x. 1 root root 36003713 Feb 14 20:15 consul
-rw-r--r--. 1 root root  8764587 Mar  1 08:50 consul_1.2.3_linux_amd64.zip

執行以下 ./consul 出現以下資訊就說明安裝成功 

[[email protected] soft]# ./consul
usage: consul [--version] [--help] <command> [<args>]

Available commands are:
    agent          Runs a Consul agent
    configtest     Validate config file
    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
    version        Prints the Consul version
    watch          Watch for changes in Consul

啟動consul (我的虛擬機器IP是192.168.0.132)

./consul agent -dev -ui -node=consul-dev -client=192.168.0.132

出現以下資訊,說明consul已在啟動

[[email protected] soft]# ./consul agent -dev -ui -node=consul-dev -client=192.168.0.132
==> Starting Consul agent...
==> Starting Consul agent RPC...
==> Consul agent running!
           Version: 'v1.2.3'
           Node ID: '564da851-08d0-5ca7-732d-220ea19adae9'
         Node name: 'consul-dev'
        Datacenter: 'dc1'
            Server: true (bootstrap: false)
       Client Addr: 192.168.0.132 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
      Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
             Atlas: <disabled>

==> Log data will now stream in as it occurs:

    2018/09/22 19:14:43 [DEBUG] Using unique ID "564da851-08d0-5ca7-732d-220ea19adae9" from host as node ID
    2018/09/22 19:14:43 [INFO] raft: Initial configuration (index=1): [{Suffrage:Voter ID:127.0.0.1:8300 Address:127.0.0.1:8300}]
    2018/09/22 19:14:43 [INFO] raft: Node at 127.0.0.1:8300 [Follower] entering Follower state (Leader: "")
    2018/09/22 19:14:43 [INFO] serf: EventMemberJoin: consul-dev 127.0.0.1
    2018/09/22 19:14:43 [INFO] consul: Adding LAN server consul-dev (Addr: tcp/127.0.0.1:8300) (DC: dc1)
    2018/09/22 19:14:43 [INFO] serf: EventMemberJoin: consul-dev.dc1 127.0.0.1
    2018/09/22 19:14:43 [INFO] consul: Adding WAN server consul-dev.dc1 (Addr: tcp/127.0.0.1:8300) (DC: dc1)
    2018/09/22 19:14:50 [WARN] raft: Heartbeat timeout from "" reached, starting election
    2018/09/22 19:14:50 [INFO] raft: Node at 127.0.0.1:8300 [Candidate] entering Candidate state in term 2
    2018/09/22 19:14:50 [DEBUG] raft: Votes needed: 1
    2018/09/22 19:14:50 [DEBUG] raft: Vote granted from 127.0.0.1:8300 in term 2. Tally: 1
    2018/09/22 19:14:50 [INFO] raft: Election won. Tally: 1
    2018/09/22 19:14:50 [INFO] raft: Node at 127.0.0.1:8300 [Leader] entering Leader state
    2018/09/22 19:14:50 [INFO] consul: cluster leadership acquired
    2018/09/22 19:14:50 [INFO] consul: New leader elected: consul-dev
    2018/09/22 19:14:50 [DEBUG] consul: reset tombstone GC to index 3
    2018/09/22 19:14:50 [INFO] consul: member 'consul-dev' joined, marking health alive
    2018/09/22 19:14:51 [INFO] agent: Synced service 'consul'
    2018/09/22 19:14:51 [DEBUG] agent: Node info in sync
==> Failed to check for updates: Get https://checkpoint-api.hashicorp.com/v1/check/consul?arch=amd64&os=linux&signature=&version=1.2.3: net/http: TLS handshake timeout
    2018/09/22 19:15:19 [DEBUG] agent: Service 'consul' in sync
    2018/09/22 19:15:19 [DEBUG] agent: Node info in sync
    2018/09/22 19:16:15 [DEBUG] agent: Service 'consul' in sync
    2018/09/22 19:16:15 [DEBUG] agent: Node info in sync
    2018/09/22 19:16:44 [DEBUG] http: Request GET /v1/catalog/datacenters (49.937碌s) from=192.168.0.132:38143
    2018/09/22 19:16:49 [DEBUG] http: Request GET /v1/catalog/datacenters (28.699碌s) from=192.168.0.132:38143
    2018/09/22 19:16:49 [DEBUG] http: Request GET /v1/internal/ui/nodes?dc=dc1&token=<hidden> (526.341碌s) from=192.168.0.132:38144
    2018/09/22 19:16:49 [DEBUG] http: Request GET /v1/coordinate/nodes?dc=dc1&token=<hidden> (99.51碌s) from=192.168.0.132:38143
    2018/09/22 19:16:49 [DEBUG] http: Request GET /v1/internal/ui/services?dc=dc1&token=<hidden> (92.846碌s) from=192.168.0.132:38143
    2018/09/22 19:16:49 [DEBUG] agent: Service 'consul' in sync
    2018/09/22 19:16:49 [DEBUG] agent: Service 'consul' in sync
    2018/09/22 19:16:49 [DEBUG] agent: Node info in sync

二、springcloud consul實現

1、建立名springcloud-consul的springboot工程

pom.xml依賴檔案:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example.demo</groupId>
	<artifactId>springcloud-consul</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<name>springcloud-consul</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>com.example</groupId>
		<artifactId>springcloud-master</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</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>Finchley.RELEASE</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</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>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2、application.yml配置檔案:

server:
  port: 8081

spring:
  cloud:
    consul:
      host: 192.168.0.132
      port: 8500
      discovery:
        healthCheckPath: ${management.context-path}/health
        healthCheckInterval: 15s
        instance-id: consul-server
  application:
    name: consul-server

3、啟動類添加註解@EnableDiscoveryClient 

package com.example.demo.consul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class SpringcloudConsulApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringcloudConsulApplication.class, args);
	}
}

4、建立訪問介面TestController.java檔案

package com.example.demo.consul.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 路徑:com.example.demo.consul.controller
 * 類名:
 * 功能:《用一句描述一下》
 * 備註:
 * 建立人:typ
 * 建立時間:2018/9/22 19:55
 * 修改人:
 * 修改備註:
 * 修改時間:
 */
@RestController
public class TestController {

    @GetMapping("/test")
    public String test(){
        return "Holle World!";
    }
}
Holle World!