.Net Core 商城微服務項目系列(二):使用Ocelot + Consul構建具備服務注冊和發現功能的網關...

1.服務注冊

在上一篇的鑒權和登錄服務中分別通過NuGet引用Consul這個包,同時新增AppBuilderExtensions類:

    public static class AppBuilderExtensions{public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app,IApplicationLifetime lifetime,ServiceEntity serviceEntity){var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//請求注冊的Consul地址var httpCheck = new AgentServiceCheck(){DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(5),//服務啟動多久后注冊Interval=TimeSpan.FromSeconds(10),//健康檢查時間間隔,或者成為心跳間隔HTTP=$"http://{serviceEntity.IP}:{serviceEntity.Port}/api/health",//健康檢查地址Timeout=TimeSpan.FromSeconds(5)};//Register service with consulvar registration = new AgentServiceRegistration(){Checks = new[] {httpCheck},ID=Guid.NewGuid().ToString(),Name=serviceEntity.ServiceName,Address=serviceEntity.IP,Port=serviceEntity.Port,Tags = new[] { $"urlprefix-/{serviceEntity.ServiceName}"} //添加urlprefix-/servicename格式的tag標簽,以便Fabio識別
            };consulClient.Agent.ServiceRegister(registration).Wait();//服務啟動時注冊,內部實現其實就是使用Consul API進行注冊(HttpClient發起)lifetime.ApplicationStopping.Register(() =>{consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服務停止時取消注冊
            });return app;}}public class ServiceEntity{public string IP { get; set; }public int Port { get; set; }public string ServiceName { get; set; }public string ConsulIP { get; set; }public int ConsulPort { get; set; }}

通過這個類可以提供服務注冊的基本參數。

修改Startup啟動項中的Configure方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}#region Consul 服務注冊ServiceEntity serviceEntity = new ServiceEntity{IP = "127.0.0.1",   //服務運行地址Port = Convert.ToInt32(Configuration["Consul:ServicePort"]), //服務運行端口ServiceName = Configuration["Consul:Name"], //服務標識,Ocelot中會用到ConsulIP = Configuration["Consul:IP"], //Consul運行地址ConsulPort = Convert.ToInt32(Configuration["Consul:Port"])  //Consul運行端口(默認8500)
            };app.RegisterConsul(lifetime, serviceEntity);#endregionapp.UseIdentityServer();//app.UseAuthentication();
            app.UseStaticFiles();app.UseMvcWithDefaultRoute();}

看下配置文件需要新增的東西:

{"Service": {"Name": "MI.Service","Port": "7001","DocName": "Account Service","Version": "v1","Title": "Account Service API"},"Identity": {"IP": "localhost","Port": "7000","Scheme": "Bearer"},"ConnectionStrings": {"SqlConnection": "server=.;uid=sa;pwd=sa;database=MI"},"Consul": {"Name": "MI.Service.Account","ServiceProt": "7001","IP": "localhost","Port": "8500"}
}

藍色標識的Consul部分是我們這里需要用到的,這里我把項目名稱當作服務注冊標識。

然后還需要為兩個服務添加兩個方法,一個是用來做健康檢查的,一個是用來測試的:

    [Route("api/Health")]public class HealthController : Controller{[HttpGet]public IActionResult Get() => Ok("ok");}
public class MiUserController : Controller{public MIContext _context;public MiUserController(MIContext _context){this._context = _context;}public string Index(){return "Successful";}。。。。。。
}

?

通過“consul agent -dev”命令運行Consul,訪問127.0.0.1:8500我們可以看到Consul的UI界面:

這里可以看到我們已經注冊的兩個服務。

?

2.服務發現

新建API項目MI.Ocelot,通過NuGet引用Ocelot和Ocelot.Provider.Consul兩個包,并修改啟動項注冊Ocelot和Consul:

public void ConfigureServices(IServiceCollection services){//services.AddMvc();
            services.AddOcelot(Configuration).AddConsul();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseOcelot();//app.UseMvc();  }

然后添加配置文件consul.json:

{"ReRoutes": [{"UseServiceDiscovery": true, //啟用服務發現"DownstreamPathTemplate": "/Account/{url}", //下游轉發路由"DownstreamScheme": "http", //標識頭"ServiceName": "MI.Service.Account", //服務注冊標識"LoadBalancer": "RoundRobin", //服務均衡:輪詢"UpstreamPathTemplate": "/Account/{url}", //上游請求路由"UpstreamHttpMethod": [ "Get", "Post" ], //請求的方法類型"ReRoutesCaseSensitive": false //不區分大小寫
    },{"UseServiceDiscovery": true,"DownstreamPathTemplate": "/Identity/{url}","DownstreamScheme": "http","ServiceName": "MI.Service.IdentityServer","LoadBalancer": "RoundRobin","UpstreamPathTemplate": "/Identity/{url}","UpstreamHttpMethod": [ "Get", "Post" ],"ReRoutesCaseSensitive": false}],"GlobalConfiguration": {//"BaseUrl": "http://localhost:7003","ServiceDiscoveryProvider": {"Host": "127.0.0.1", // Consul Service IP"Port": 8500, // Consul Service Port"Type": "PollConsul","PollingInterval": 100 //健康檢查時間端
    }}
}

在Program中啟用這個配置文件:

        public static IWebHost BuildWebHost(string[] args) =>WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().ConfigureAppConfiguration((hostingContext,builder)=> {builder.AddJsonFile("consul.json");}).Build();

到此,網關配置完畢。現在我將網關項目MI.Gateway部署在7003端口,登錄服務MI.Service.Account部署在7001端口,鑒權服務部署在7000端口,我會通過訪問網關服務來請求登錄服務:

這里的流程是這樣的,Ocelot通過“/Account/MiUser/Index”匹配到了“/Account/{url}”這個路由,進而拿到了“MI.Service.Account”這個服務注冊標識,然后通過Consul拿到了對應的地址,并轉發了請求,同時返回結果。

?

到此,具備服務注冊和發現的簡單網關服務就搭建完畢了,后面有時間會繼續優化,添加限流、熔斷,同時身份驗證會在Ocelot中進行,而不是再去訪問單獨的鑒權服務。

?

轉載于:https://www.cnblogs.com/weiBlog/p/9833807.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/396398.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396398.shtml
英文地址,請注明出處:http://en.pswp.cn/news/396398.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java打印數組_Java中打印數組內容的方式有哪些?

下面是幾種常見的打印方式。方法一&#xff1a;使用循環打印。public class Demo {public static void main(String[] args) {String[] infos new String[] {"Java", "Android", "C/C", "Kotlin"};StringBuffer strBuffer new Strin…

$(function() {})

$(function() {});是$(document).ready(function(){ })的簡寫&#xff0c; 最早接觸的時候也說$(document).ready(function(){ })這個函數是用來取代頁面中的window.onload; 用來在DOM加載完成之后執行一系列預先定義好的函數。

恢復工具

EasyRecovery http://www.upantool.com/hfxf/huifu/2011/EasyRecovery_V6.22.html轉載于:https://www.cnblogs.com/cb168/p/5359133.html

四參數坐標轉換c++_GPSRTK坐標轉換及四參數、七參數適用條件

工程測量儀器已由經緯儀、全站儀過渡到GNSS(全球衛星導航系統)&#xff0c;特別是公路行業&#xff0c;GPS-RTK作為GNSS的一種應用目前已十分普及。現階段GPS-RTK以WGS-84 坐標系統為主流&#xff0c;所發布的星歷參數也是基于此坐標系統&#xff0c;但隨著北斗導航系統的逐步完…

教主的魔法

傳送門 這道題序列很長&#xff0c;但是操作數很少&#xff0c;然后也沒想到什么好的數據結構來維護&#xff0c;那就分塊吧。 感覺維護的過程很好想&#xff0c;修改的時候對于整個塊都在內的直接打標記&#xff0c;兩個零散的區間暴力重構&#xff0c;重新排序。查詢的時候&a…

obs自定義編碼設置_通過7個步驟設置OBS進行實時編碼

obs自定義編碼設置by Wesley McCann韋斯利麥肯(Wesley McCann) 通過7個步驟設置OBS進行實時編碼 (Setting up OBS for Live Coding in 7 Steps) Twitch TV is a popular live-streaming service. You traditionally used Twitch to stream yourself playing video games, but …

java hadoop api_Hadoop 系列HDFS的Java API( Java API介紹)

HDFS的Java APIJava API介紹將詳細介紹HDFS Java API&#xff0c;一下節再演示更多應用。Java API 官網如上圖所示&#xff0c;Java API頁面分為了三部分&#xff0c;左上角是包(Packages)窗口&#xff0c;左下角是所有類(All Classes是)窗口&#xff0c;右側是詳情窗口。這里推…

最大連通子數組

這次是求聯通子數組的求和&#xff0c;我們想用圖的某些算法&#xff0c;比如迪杰斯特拉等&#xff0c;但是遇到了困難。用BFS搜索能達到要求&#xff0c;但是還未能成功。 那么我們這樣想&#xff0c;先將每行的最大子數組之和&#xff0c;然后再將這些最大之和組成一個數組&a…

redis的zset的底層實現_Redis(三)--- Redis的五大數據類型的底層實現

1、簡介Redis的五大數據類型也稱五大數據對象&#xff1b;前面介紹過6大數據結構&#xff0c;Redis并沒有直接使用這些結構來實現鍵值對數據庫&#xff0c;而是使用這些結構構建了一個對象系統redisObject&#xff1b;這個對象系統包含了五大數據對象&#xff0c;字符串對象(st…

科學計算機簡單編程_是“計算機科學”還是“編程”?

科學計算機簡單編程by Sam Corcos由Sam Corcos 是“計算機科學”還是“編程”&#xff1f; (Is It “Computer Science” or “Programming”?) 教育政策白皮書(提示&#xff1a;它們不是同一個東西) (An education policy white paper (hint: they’re not the same thing))…

[Matlab] 畫圖命令

matlab畫圖命令&#xff0c;不定時更新以便查找 set(gcf, color, [1 1 1]);     % 使圖背景為白色 alpha(0.4);           %設置平面透明度 plot(Circle1,Circle2,k--,linewidth,1.25);  % k--設置線型  ‘linewidth’,1.25  設置線寬度為1.25 %線型   …

django入門記錄 2

1. 創建一個app&#xff0c; python manage.py startapp appname 2. 設計model&#xff0c;在appname/目錄下編輯好model 3. 檢測model的修改&#xff0c;python manage.py makemigrations appname 4. 自動執行數據庫遷移&#xff0c;并同步管理數據庫結構&#xff0c; python…

spark sql 數據類型轉換_SparkSql 數據類型轉換

1、SparkSql數據類型 1.1數字類型 ByteType:代表一個字節的整數。范圍是-128到127 ShortType:代表兩個字節的整數。范圍是-32768到32767 IntegerType:代表4個字節的整數。范圍是-2147483648到2147483647 LongType:代表8個字節的整數。范圍是-9223372036854775808到92233720…

【Python】 list dict str

list & dict & str 這三種類型是python中最常用的幾種數據類型。他們都是序列的一種 ■  序列通用操作 1. 分片 s[a:b] 返回序列s中從s[a]到s[b-1]的片段。注意s[0:0]是空集而不是s[0] s[a:b:c]  加入第三個參數以設置取樣步長。可以設置成負數來從右向左取樣 2. 加…

終端terminal的顏色配置

PS1 color 終端terminal的顏色配置 PS1"\[\e[92;1m\][\u\e[90;5m\e[25m\[\e[91;4m\]Atlas\e[24m\[\e[1m\]\[\e[92;1m\] \W ]\\$\[\e[0m\]" Set CodeDescriptionExamplePreview1Bold/Bright echo -e "Normal \e[1mBold" 2Dim echo -e "Normal \e[2mDi…

速度與激情的Webpack

Also published in my tech blog也發布在我的技術博客中 This is a guide that is meant to help you ease your development workflow and save your time by using a bunch of awesome tools that you’ve read about on the internet (does React Hot Loader ring any bells…

java nio socket長連接_nio實現Socket長連接和心跳

前段時間用bio方式&#xff0c;也就是傳統io實現了socket的長連接和心跳&#xff0c;總覺著服務端開啟多線程管理socket連接的方式過于消耗資源&#xff0c;數據并發的情況下可能會影響到性能&#xff0c;因此就嘗試使用nio改進原來的代碼。然而改進的過程卻不像我起初設想的那…

unity讓對象作為參數_C#+Unity學習筆記:類與對象

參考文獻蜜酒廳通訊社 游戲部 石中居士對象(object)&#xff1a;有狀態、行為和身份的東西。狀態(state)&#xff1a;表示物體特征的信息&#xff0c;可以用來跟蹤對象的狀態。屬性(properties)&#xff1a;因為編程人員需要把控對象的狀態&#xff0c;所以要對其進行訪問。通過…

Tomcat 報 The valid characters are defined in RFC 7230 and RFC 3986

問題 24-Mar-2017 23:43:21.300 INFO [http-apr-8001-exec-77] org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level. java.lang.IllegalAr…

Linux Kernel Oops異常分析

0&#xff0e;linux內核異常常用分析方法 異常地址是否在0附近&#xff0c;確認是否是空指針解引用問題異常地址是否在iomem映射區&#xff0c;確認是否是設備訪問總線異常問題&#xff0c;如PCI異常導致的地址訪問異常異常地址是否在stack附近&#xff0c;如果相鄰&#xff0c…