我是服務的執政官-服務發現和注冊工具consul簡介


服務發現和注冊


我們有了兩個服務。服務A的IP地址是192.168.0.1,端口9001,服務B的IP地址192.168.0.2,端口9002。我們的客戶端需要調用服務A和服務B,我們只需要在配置文件中寫上服務A和服務B的IP地址即可。

此時,服務A的服務器負載有點高,我們需要臨時增加服務A的實例,IP192.168.0.3,端口9001。但是我們的客戶端要怎么才能調用新的實例?

常規來說,我們可以有以下幾種方法:

  • 網絡代理方式
    如果是http方式通信的服務,可以增加一個nginx做反向代理,轉發到兩個服務A的實例上。
    如果是RPC服務則可以增加一個LVS或HAProxy或者ESB之類的網絡代理,客戶端配置網絡代理地址。
    服務B我們再來一套一樣的配置,這時候又來了服務C、服務D、服務E...,好吧我們好還要再多維護同樣多的網絡代理。此外,所有的服務調用服務調用都必須經過網絡代理,我們還必須保證代理的高可用。最后,陷入運維災難。

  • DNS方式
    給服務A配置一個域名,然后通過配置兩個A記錄分別指向兩個服務A的實例,客戶端只要配置服務A的域名即可。
    這種方式也存在問題,首先DNS沒有辦法管理端口,我們的端口還是只能寫在每個客戶端的配置文件中。此外DNS輪詢負載均衡能力太弱,可能會導致客戶端負載的不均衡。

現在有了服務發現和注冊機制,我們可以更合理的解決這個問題。

服務發現和注冊,參考字面意思很容易理解,其核心部分可以理解為一個服務注冊表。服務啟動時,將自己的信息注冊到注冊表中。注冊表需要每一定時間訪問下已經注冊的服務,將沒有響應的服務從注冊表中刪除。最終讓客戶端拿到正常運行的服務地址。

此時,我們的服務注冊表必須具備分布式、高可用、強一致性等特點。

目前,業界開源的服務發現和注冊產品有很多,比較流行的主要有:ZooKeeper,Etcd,Consul,Eureka等。

下面介紹下今天的主角,Consul

Consul


Consul是一個服務發現和注冊的工具,其具有分布式、高擴展性能特點。

Consul主要包含如下功能:

  • 服務發現: 支持 http 和 dns 兩種協議的服務注冊和發現方式。
  • 監控檢查: 支持多種方式的健康檢查。
  • Key/Value存儲: 支持通過HTTP API實現分布式KV數據存儲。
  • 多數據中心支持:支持任意數量數據中心。

官網圖

上圖是官網提供的一個事例系統圖,圖中的Server是consul服務端高可用集群,Client是consul客戶端。consul客戶端不保存數據,客戶端將接收到的請求轉發給響應的Server端。Server之間通過局域網或廣域網通信實現數據一致性。每個Server或Client都是一個consul agent。Consul集群間使用了GOSSIP協議通信和raft一致性算法。

使用Consul也非常簡單,基本可以做到開箱即用。

下載應用后可以通過簡單的腳本啟動服務端和客戶端:

$ 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
version        Prints the Consul version
watch          Watch for changes in Consul

運行consul agent 加上相關的參數,就可以啟動一個consul server 或者 client。

接着,我們可以通過http api注冊服務,向/v1/catalog/register發送PUT動作的JSON報文:

{
  "Datacenter": "dc1",   
  "Node": "foobar",	     
  "Address": "192.168.10.10",  
  "Service": {             //注冊的服務信息
    "ID": "redis1",
    "Service": "redis",
    "Tags": [
      "primary",
      "v1"
    ],
    "Address": "127.0.0.1",
    "Port": 8000
  },
  "Check": {              //注冊健康檢查
    "Node": "foobar",
    "CheckID": "service:redis1",
    "Name": "Redis health check",
    "Notes": "Script based health check",
    "Status": "passing",
    "ServiceID": "redis1"
  }
}

注冊后,我們可以在consul自帶的WEB UI中看到剛剛注冊的服務:

與Spring Cloud集成


如果你的服務正好使用spring boot構建,不妨試試Spring Cloud Consul

Spring Cloud Consul通過幾個簡單的注解,就可以集成諸多consul功能,讓你更方便的治理你的服務。

@SpringBootApplication
@EnableDiscoveryClient   //只要添加這個注解即可向配置號的consul注冊服務
@RestController
public class Application { 
    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    } 
}

同時我們可以配合spring boot actuator來注冊監控檢查:

spring:
  cloud:
    consul:
      discovery:
        healthCheckPath: ${management.contextPath}/health
        healthCheckInterval: 15s

Spring Cloud支持 Feign 或者 Spring RestTemplate 通過服務發現來調用服務,也可以使用org.springframework.cloud.client.discovery.DiscoveryClient:

@Autowired //注入一個DiscoveryClient
private DiscoveryClient discoveryClient;

public String serviceUrl() {
    List<ServiceInstance> list = discoveryClient.getInstances("STORES");
    if (list != null && list.size() > 0 ) {
        return list.get(0).getUri();
    }
    return null;
}

consul除了可以用作服務治理的工具,還可以利用其KV存儲能力,實現分布式服務配置或分布式鎖等功能。各位感興趣的童鞋可以去consul官網,學習更多的內容。

最后,都看到這了,就順手點個贊吧~~~

參考資料:
https://www.nginx.com/blog/service-discovery-in-a-microservices-architecture/
https://highops.com/insights/service-discovery-6-questions-to-4-experts/
https://www.consul.io/
http://cloud.spring.io/spring-cloud-consul/


免責聲明!

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



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