Asp-Net Core Ocelot Consul 微服務

做一個簡單的微服務架構如下圖:

這個圖表示的是一個網關代理 Consul 的兩個服務,consul 每個服務註冊集羣

安裝 Consul 的服務,這裏安裝單機版的,集羣版配置最低要求(3 個 Consul server)的需要三臺虛擬機,窮
這是下載地址 Consul 我這裏部署的是 CentOS7 ip 是:192.168.31.140 記得關閉防火牆

 1yum instarll wget -y
 2yum instarll unzip -y
 3wget  https://releases.hashicorp.com/consul/1.7.2/consul_1.7.2_linux_amd64.zip
 4unzip consul_1.7.2_linux_amd64.zip
 5mv consul /usr/local/bin/
 6consul -v 查看圖一代表安裝成功了
 7nohup consul agent -server -ui -bootstrap-expect=1 -data-dir=/tmp/consul  -node=consul-1 -client=0.0.0.0   -datacenter=dc1 & 後臺啓動會生成一個nohup.out的日子文件
 8curl http://127.0.0.1:8500/ui/dc1/services  訪問 如下圖二代表服務啓動OK
 9consul可以通過配置文件註冊服務,我這裏用的是api代碼註冊
10配置文件註冊vi /etc/consul/services_config.json創建配置文件重啓即可
11
12

圖一

圖二

接下來寫 ServiceUser 的服務,選擇 asp.net core Api 模板創建項目,安裝 Consul 包

添加一個健康檢查的 API 直接返回 OK

再添加一個返回用戶數據的 API

在寫一個服務註冊的方法在 Startup.cs 裏,ip 和 port 及 id 我是從命令行獲取的其他配置均寫在配置文件裏

 1       private static void ServiceRegister(IConfiguration configuration)
 2        {
 3            
 4            ConsulClient client = new ConsulClient(new Action<ConsulClientConfiguration>(t => {
 5                t.Address = new Uri(configuration["consul:servicesAddr"]);//這是Consul的服務地址192.168.31.140
 6                t.Datacenter = configuration["consul:datacenter"];//儲存名
 7            }));
 8            //註冊一個實例
 9            var result = client.Agent.ServiceRegister(new AgentServiceRegistration()
10            {
11                Address = configuration["ip"], //註冊服務的IP
12                ID = $"{configuration["consul:serviceName"]}{configuration["id"]}",//服務id唯一的
13                Name = configuration["consul:serviceName"],//服務名
14                Port = Convert.ToInt32(configuration["port"]),//端口
15                Tags = null,
16                Check = new AgentServiceCheck()
17                {
18                    HTTP = $"http://{configuration["ip"]}:{configuration["port"]}{configuration["consul:healthCheck"]}",//健康檢查的API地址
19                    Interval = new TimeSpan(0, 0, 10),//間隔多少檢查一次
20                    DeregisterCriticalServiceAfter = new TimeSpan(0, 1, 0) //多久註銷不健康的服務
21                }
22            }).Result;
23        }
24
25

獲取命令行參數 寫在 main 方法裏如下圖

1new ConfigurationBuilder()
2                .SetBasePath(Directory.GetCurrentDirectory())
3                .AddCommandLine(args).Build();
4
5

編寫配置文件

1  "consul": {
2    "servicesAddr": "http://192.168.31.140:8500",
3    "datacenter": "dr1",
4    "serviceName": "ServiceCommodity",
5    "healthCheck": "/api/Health"
6  }
7
8

ServiceCommodity 和 ServiceUser 一樣

接下來啓動實例註冊服務,我這裏用端口區分不同的實例

1dotnet ServiceCommodity.dll --urls http://*:5000  --environment Development --ip 192.168.31.137 --port 5000 --id 1
2dotnet ServiceCommodity.dll --urls http://*:5001  --environment Development --ip 192.168.31.137 --port 5001 --id 2
3dotnet ServiceCommodity.dll --urls http://*:5002  --environment Development --ip 192.168.31.137 --port 5002 --id 3
4dotnet ServiceUser.dll --urls http://*:6000  --environment Development --ip 192.168.31.137 --port 6000 --id 1
5dotnet ServiceUser.dll --urls http://*:6001  --environment Development --ip 192.168.31.137 --port 6001 --id 2
6dotnet ServiceUser.dll --urls http://*:6002  --environment Development --ip 192.168.31.137 --port 6002 --id 3
7
8


接下來註冊 Ocelot 網關,微服務是離不開網關的,現在可能看不出網關的效果,Consul 搭建成集羣就能看出效果了
創建一個空的 web 項目安裝如下兩個包

在 Startup.cs 裏註冊

創建 ocelot.json 配置文件

 1{
 2  "ReRoutes": [
 3    {
 4      "DownstreamPathTemplate": "/api/{controller}",//你的api路徑
 5      "DownstreamScheme": "http",
 6      "UpstreamPathTemplate": "/dust/{controller}",//你映射的路徑
 7      "UpstreamHttpMethod": [ "get", "post" ],//請求方法
 8      "ServiceName": "ServiceCommodity",//你的服務名稱
 9      "LoadBalancerOptions": {
10        "Type": "LeastConnection"//ocelot提供了幾種均衡方法,這裏用的是最小連接
11      }
12    },
13    {
14        "DownstreamPathTemplate": "/api/{controller}",
15        "DownstreamScheme": "http",
16        "UpstreamPathTemplate": "/dust1/{controller}",
17        "UpstreamHttpMethod": [ "get", "post" ],
18        "ServiceName": "ServiceUser",
19        "LoadBalancerOptions": {
20          "Type": "LeastConnection"
21        }
22    }
23  ],
24  "GlobalConfiguration": {
25    "ServiceDiscoveryProvider": {
26      "Host": "192.168.31.140",//你的Consul的ip地址
27      "Port": 8500,//你的Consul的端口
28      "ConfigurationKey": "Consul"//指定Consul,ocelot提供了幾種,可以去官網看看
29    }
30
31  }
32}
33
34

加載配置文件

 1  .ConfigureAppConfiguration((hostingContext, config) =>
 2               {
 3                   config
 4                       .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
 5                       .AddJsonFile("appsettings.json", true, true)
 6                       .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
 7                       .AddJsonFile("ocelot.json")
 8                       .AddEnvironmentVariables();
 9               })
10
11

1啓動 dotnet GateWayOcelot.dll --urls http://*:7000
2
3

最後應用請求網關

 1  string[] userAry = null;
 2            string[] commodityAry = null;
 3            using (HttpClient httpClient = new HttpClient())
 4            {
 5                HttpResponseMessage httpResponseMessage  = httpClient.GetAsync("http://192.168.31.137:7000/dust1/user").Result;
 6
 7                userAry = JsonConvert.DeserializeObject<string[]>(httpResponseMessage.Content.ReadAsStringAsync().Result);
 8            }
 9            using (HttpClient httpClient = new HttpClient())
10            {
11                HttpResponseMessage httpResponseMessage = httpClient.GetAsync("http://192.168.31.137:7000/dust/commodity").Result;
12
13                commodityAry = JsonConvert.DeserializeObject<string[]>(httpResponseMessage.Content.ReadAsStringAsync().Result);
14            }
15            this.ViewBag.msgText = $"{userAry[0]}和{userAry[1]}討論項目,去燒烤攤點了{commodityAry[0]},{commodityAry[1]},{commodityAry[2]},第二天凌晨5點兩個人支起了早餐攤!";
16
17

到此一個簡單的微服務 OK 了

Demo 下載地址: https://github.com/Xiao-Dust/MicroService

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/Ta_BRNvV_dWIEahJogKoPA