日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

Asp.Net Core Ocelot Consul 微服务

發布時間:2023/12/4 asp.net 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Asp.Net Core Ocelot Consul 微服务 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

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

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

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

圖一

圖二

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

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

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

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

private static void ServiceRegister(IConfiguration configuration){ConsulClient client = new ConsulClient(new Action<ConsulClientConfiguration>(t => {t.Address = new Uri(configuration["consul:servicesAddr"]);//這是Consul的服務地址192.168.31.140t.Datacenter = configuration["consul:datacenter"];//儲存名}));//注冊一個實例var result = client.Agent.ServiceRegister(new AgentServiceRegistration(){Address = configuration["ip"], //注冊服務的IPID = $"{configuration["consul:serviceName"]}{configuration["id"]}",//服務id唯一的Name = configuration["consul:serviceName"],//服務名Port = Convert.ToInt32(configuration["port"]),//端口Tags = null,Check = new AgentServiceCheck(){HTTP = $"http://{configuration["ip"]}:{configuration["port"]}{configuration["consul:healthCheck"]}",//健康檢查的API地址Interval = new TimeSpan(0, 0, 10),//間隔多少檢查一次DeregisterCriticalServiceAfter = new TimeSpan(0, 1, 0) //多久注銷不健康的服務}}).Result;}

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

new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddCommandLine(args).Build();

編寫配置文件

"consul": {"servicesAddr": "http://192.168.31.140:8500","datacenter": "dr1","serviceName": "ServiceCommodity","healthCheck": "/api/Health"}

ServiceCommodity和ServiceUser一樣

接下來啟動實例注冊服務,我這里用端口區分不同的實例

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


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

在Startup.cs 里注冊

創建ocelot.json配置文件

{"ReRoutes": [{"DownstreamPathTemplate": "/api/{controller}",//你的api路徑"DownstreamScheme": "http","UpstreamPathTemplate": "/dust/{controller}",//你映射的路徑"UpstreamHttpMethod": [ "get", "post" ],//請求方法"ServiceName": "ServiceCommodity",//你的服務名稱"LoadBalancerOptions": {"Type": "LeastConnection"//ocelot提供了幾種均衡方法,這里用的是最小連接}},{"DownstreamPathTemplate": "/api/{controller}","DownstreamScheme": "http","UpstreamPathTemplate": "/dust1/{controller}","UpstreamHttpMethod": [ "get", "post" ],"ServiceName": "ServiceUser","LoadBalancerOptions": {"Type": "LeastConnection"}}],"GlobalConfiguration": {"ServiceDiscoveryProvider": {"Host": "192.168.31.140",//你的Consul的ip地址"Port": 8500,//你的Consul的端口"ConfigurationKey": "Consul"//指定Consul,ocelot提供了幾種,可以去官網看看}} }

加載配置文件

.ConfigureAppConfiguration((hostingContext, config) =>{config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath).AddJsonFile("appsettings.json", true, true).AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true).AddJsonFile("ocelot.json").AddEnvironmentVariables();})

啟動 dotnet GateWayOcelot.dll --urls http://*:7000

最后應用請求網關

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

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


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

往期精彩回顧

  • .netcore consul實現服務注冊與發現(一)單機部署

  • .netcore consul實現服務注冊與發現(二)集群完整版

  • 基于Docker的Consul服務發現集群搭建

  • Ocelot簡易教程(五)之集成IdentityServer認證以及授權


點擊【在看】+轉發【朋友圈】對我最大的支持

總結

以上是生活随笔為你收集整理的Asp.Net Core Ocelot Consul 微服务的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。