Consul最常用的就是服務注冊與發現,健康檢查,接下來演示一下在Windows上如何使用
Step1:在官網下載consul.exe(下載較慢,耐心等待)
Step2:cmd到這個路徑下,輸入consul.exe agent -dev開啟后,打開http://localhost:8500/
Step3:在代碼中,進行服務注冊

public static class ConsulHelper { public static void Init( this IConfiguration _configuration) { ConsulClient clinet = new ConsulClient(c => { c.Address = new Uri("http://localhost:8500/"); c.Datacenter = "dcl"; }); string ip = _configuration["ip"]; int port = int.Parse(_configuration["port"]); clinet.Agent.ServiceRegister(new AgentServiceRegistration() { ID="service"+Guid.NewGuid(), Name="shenqing", Address = ip, Port = port, Check = new AgentServiceCheck() { Interval = TimeSpan.FromSeconds(12),//間隔12秒一次 HTTP = $"http://{ip}:{port}/API/Health/Index", Timeout = TimeSpan.FromSeconds(52),//檢測等待時間 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60)//失敗多久后移除,最小值60秒 } }).Wait(); } }
Step4:示例 同一個服務,用三個不同的端口開啟
Step5:此時查看Consuly頁面,可以看到已經有3個service
暫停一個服務后,頁面可看到一個X,並在你配置的一段時間后,會在列表里移除,這就是健康檢查。