Consul服務註冊發現與健康檢查

一、Consul概述 

consul是一個開源的使用go語言開發的服務發現、配置管理中心服務。內置了服務註冊與發現框 架、分佈一致性協議實現、健康檢查、Key/Value存儲、多數據中心方案,不再需要依賴其他工具(比如ZooKeeper等)

我們爲了服務的高可用,往往會搭建集羣,並且這些集羣是不固定的。舉個例子淘寶平時1000臺服務器就能滿足需求,但是雙11期間可能需要擴充到10000萬臺服務器,等雙11過去後,再裁減到1000臺。我們總不能在上端程序(客戶端)配置這麼多服務器的ip地址吧。服務器的添加和刪除都得更新上端程序代碼,這顯然是不現實的。我們引入Consul就能解決這一問題,上端程序需要調用服務時,無需知道有多少天服務器,服務器端口設計什麼,直接調用Consul,由Consul爲我們調用具體的服務即服發現。我們每增添獲刪除一個服務器,都會告知Consul,這叫服務的註冊。如果某個服務器掛掉了怎麼辦呢?Consul有健康檢查的功能,他會定時詢問服務是否正常,如果不正常會斷開連接,上端程序就不會調用到掛掉的服務器而報錯。

二、Consul安裝

下載地址

官網:https://www.consul.io/

官網下載較慢,這裏提供下免費下載地址:https://download.csdn.net/download/xiaolu1014/12253778

運行

consul_1.6.2.exe agent -dev

consul的監控頁面:http://localhost:8500/ 

三、服務註冊

服務端添加擴展方法

using Consul;
using Microsoft.Extensions.Configuration;
using System;

namespace ConsulService.Extensions
{
    public class ConsulHeper
    {
        public static void UseConsul(IConfiguration configuration)
        {
            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri("http://localhost:8500/");
                c.Datacenter = "dc1";
            });
            string ip = configuration["ip"];//命令行參數必須傳入ip
            int port = int.Parse(configuration["port"]);//命令行參數必須傳入端口
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = Guid.NewGuid().ToString(),//唯一的
                Name = "TestService",//組名稱-Group
                Address = ip,//其實應該寫ip地址
                Port = port,//不同實例
                Tags = null
            });

        }
    }
}

Startup

 找到項目所在文件目錄cmd,通過命令行啓動多個程序,分別爲6666端口、7777端口、8888端口

dotnet Cluster.dll --urls="http://*:6666" --ip="127.0.0.1" --port=6666
dotnet Cluster.dll --urls="http://*:7777" --ip="127.0.0.1" --port=7777
dotnet Cluster.dll --urls="http://*:8888" --ip="127.0.0.1" --port=8888

 然後進入Consul監控頁面會發現三個TestServer的服務實例證明我們的服務已經成功註冊

 

四、服務發現 

我們已經把集羣服務註冊到了Consul中,那麼下一步要做的就是讓調用端發現服務

using (ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri("http://localhost:8500/");
                c.Datacenter = "dc1";
            }))
                var dictionary = client.Agent.Services().Result.Response;
                foreach (var keyValuePair in dictionary)
                {
                    AgentService agentService = keyValuePair.Value;
                    this._logger.LogWarning($"{agentService.Address}:{agentService.Port} {agentService.ID} {agentService.Service}");
                }

五、健康檢查

健康檢查也叫心跳檢查,顧名思義就是類似心跳在一定的時間間隔去訪問下服務端,如果服務端沒有響應即判定該服務死亡,然後把它從Consul中剔除,這樣我們的調用端就不會請求到已經死亡的服務了。

健康檢查是一個持續頻繁的訪問,所以不能對真實的業務邏輯進行檢測,我們可以建一個新的控制器用於響應健康檢查。

        public IActionResult Index()
        {
            return Ok();//HttpStatusCode--200
        }

新建一個方法,返回Ok()即http狀態碼200 即可。

修改之前的服務註冊代碼,加入健康檢測代碼

using Consul;
using Microsoft.Extensions.Configuration;
using System;

namespace ConsulService.Extensions
{
    public class ConsulHeper
    {
        public static void UseConsul(IConfiguration configuration)
        {
            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri("http://localhost:8500/");
                c.Datacenter = "dc1";
            });
            string ip = configuration["ip"];//命令行參數必須傳入ip
            int port = int.Parse(configuration["port"]);//命令行參數必須傳入端口
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = Guid.NewGuid().ToString(),//唯一的
                Name = "TestService",//組名稱-Group
                Address = ip,//其實應該寫ip地址
                Port = port,//不同實例
                Tags = null, 
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(12),
                    HTTP = $"http://{ip}:{port}/Api/Health/Index",
                    Timeout = TimeSpan.FromSeconds(5),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5)
                }

            });

        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章