上一篇 consul在centos7下實現集群 講到consul的安裝和集群,本次來說一下asp.net core使用consul注冊服務
1. 准備
安裝了consul的centos7系統
三個asp.net core api項目,其中一個網關項目,兩個服務,一般微服務都會使用網關,所以這里也加上網關
項目將發布在本機IIS上(ip:192.168.1.155),consul在虛擬機(系統centos7,ip:192.168.253.128)
2. 代碼
服務A:添加HealthController,健康檢查用,然后發布到IIS,使用端口9001
[Produces("application/json")] [Route("api/[controller]")] [ApiController] public class HealthController : ControllerBase { [HttpGet] public IActionResult Get() => Ok("ok"); }
服務B:與服務A一樣,添加HealthController,內容一樣,然后發布到IIS,使用端口9002
網關項目:nuget引用ocelot包,然后在項目根目錄下添加ocelot.json文件
{ "ReRoutes": [ { "UpstreamPathTemplate": "/a/{url}", "UpstreamHttpMethod": [ "Get", "Post" ], "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 9001 } ] }, { "UpstreamPathTemplate": "/b/{url}", "UpstreamHttpMethod": [ "Get", "Post" ], "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 9002 } ] } ], "GlobalConfiguration": { } }
然后在Startup的ConfigureServices方法中添加如下代碼:
services.AddOcelot(new ConfigurationBuilder().AddJsonFile("ocelot.json", false, true).Build());
在Configure方法app.UseMvc()之前添加如下代碼
app.UseOcelot().Wait();
發布網關項目到IIS,使用9000端口
通過locaohost:9000/a/health即可訪問localhost:9001/api/health
通過locaohost:9000/b/health即可訪問localhost:9002/api/health
3. consul服務注冊(配置文件方式)
在 /etc/consul目錄下創建consul_config.json
{ "services":[ { "id": "CLIENT_SERVICE_01", "name" : "ApiServiceA", "tags": [ "ApiService_01" ], "address": "192.168.1.155", "port": 9001, "checks": [ { "name": "clientservice_check", "http": "http://192.168.1.155:9001/api/health", "interval": "10s", "timeout": "5s" } ] }, { "id": "CLIENT_SERVICE_02", "name" : "ApiServiceB", "tags": [ "ApiService_02" ], "address": "192.168.1.155", "port": 9002, "checks": [ { "name": "clientservice_check", "http": "http://192.168.1.155:9002/api/health", "interval": "10s", "timeout": "5s" } ] }] }
然后執行
consul agent -server -ui -bootstrap-expect=1 -config-dir=/etc/consul -data-dir=/var/local/consul -node=consul-128 -client=0.0.0.0 -bind=192.168.253.128 -datacenter=dc1
在瀏覽器中打開192.168.253.128:8500,可以看到服務A和服務B已經注冊並能正常訪問