.Net Core 商城微服务项目系列(二):使用Ocelot + Consul构建具备服务注册和发现功能的网关...
1.服務(wù)注冊(cè)
在上一篇的鑒權(quán)和登錄服務(wù)中分別通過(guò)NuGet引用Consul這個(gè)包,同時(shí)新增AppBuilderExtensions類(lèi):
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}"));//請(qǐng)求注冊(cè)的Consul地址var httpCheck = new AgentServiceCheck(){DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(5),//服務(wù)啟動(dòng)多久后注冊(cè)Interval=TimeSpan.FromSeconds(10),//健康檢查時(shí)間間隔,或者成為心跳間隔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標(biāo)簽,以便Fabio識(shí)別 };consulClient.Agent.ServiceRegister(registration).Wait();//服務(wù)啟動(dòng)時(shí)注冊(cè),內(nèi)部實(shí)現(xiàn)其實(shí)就是使用Consul API進(jìn)行注冊(cè)(HttpClient發(fā)起)lifetime.ApplicationStopping.Register(() =>{consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服務(wù)停止時(shí)取消注冊(cè) });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; }}通過(guò)這個(gè)類(lèi)可以提供服務(wù)注冊(cè)的基本參數(shù)。
修改Startup啟動(dòng)項(xiàng)中的Configure方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}#region Consul 服務(wù)注冊(cè)ServiceEntity serviceEntity = new ServiceEntity{IP = "127.0.0.1", //服務(wù)運(yùn)行地址Port = Convert.ToInt32(Configuration["Consul:ServicePort"]), //服務(wù)運(yùn)行端口ServiceName = Configuration["Consul:Name"], //服務(wù)標(biāo)識(shí),Ocelot中會(huì)用到ConsulIP = Configuration["Consul:IP"], //Consul運(yùn)行地址ConsulPort = Convert.ToInt32(Configuration["Consul:Port"]) //Consul運(yùn)行端口(默認(rèn)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"} }藍(lán)色標(biāo)識(shí)的Consul部分是我們這里需要用到的,這里我把項(xiàng)目名稱(chēng)當(dāng)作服務(wù)注冊(cè)標(biāo)識(shí)。
然后還需要為兩個(gè)服務(wù)添加兩個(gè)方法,一個(gè)是用來(lái)做健康檢查的,一個(gè)是用來(lái)測(cè)試的:
[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";}。。。。。。 }?
通過(guò)“consul agent -dev”命令運(yùn)行Consul,訪問(wèn)127.0.0.1:8500我們可以看到Consul的UI界面:
這里可以看到我們已經(jīng)注冊(cè)的兩個(gè)服務(wù)。
?
2.服務(wù)發(fā)現(xiàn)
新建API項(xiàng)目MI.Ocelot,通過(guò)NuGet引用Ocelot和Ocelot.Provider.Consul兩個(gè)包,并修改啟動(dòng)項(xiàng)注冊(cè)O(shè)celot和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, //啟用服務(wù)發(fā)現(xiàn)"DownstreamPathTemplate": "/Account/{url}", //下游轉(zhuǎn)發(fā)路由"DownstreamScheme": "http", //標(biāo)識(shí)頭"ServiceName": "MI.Service.Account", //服務(wù)注冊(cè)標(biāo)識(shí)"LoadBalancer": "RoundRobin", //服務(wù)均衡:輪詢(xún)"UpstreamPathTemplate": "/Account/{url}", //上游請(qǐng)求路由"UpstreamHttpMethod": [ "Get", "Post" ], //請(qǐng)求的方法類(lèi)型"ReRoutesCaseSensitive": false //不區(qū)分大小寫(xiě) },{"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 //健康檢查時(shí)間端 }} }在Program中啟用這個(gè)配置文件:
public static IWebHost BuildWebHost(string[] args) =>WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().ConfigureAppConfiguration((hostingContext,builder)=> {builder.AddJsonFile("consul.json");}).Build();到此,網(wǎng)關(guān)配置完畢。現(xiàn)在我將網(wǎng)關(guān)項(xiàng)目MI.Gateway部署在7003端口,登錄服務(wù)MI.Service.Account部署在7001端口,鑒權(quán)服務(wù)部署在7000端口,我會(huì)通過(guò)訪問(wèn)網(wǎng)關(guān)服務(wù)來(lái)請(qǐng)求登錄服務(wù):
這里的流程是這樣的,Ocelot通過(guò)“/Account/MiUser/Index”匹配到了“/Account/{url}”這個(gè)路由,進(jìn)而拿到了“MI.Service.Account”這個(gè)服務(wù)注冊(cè)標(biāo)識(shí),然后通過(guò)Consul拿到了對(duì)應(yīng)的地址,并轉(zhuǎn)發(fā)了請(qǐng)求,同時(shí)返回結(jié)果。
?
到此,具備服務(wù)注冊(cè)和發(fā)現(xiàn)的簡(jiǎn)單網(wǎng)關(guān)服務(wù)就搭建完畢了,后面有時(shí)間會(huì)繼續(xù)優(yōu)化,添加限流、熔斷,同時(shí)身份驗(yàn)證會(huì)在Ocelot中進(jìn)行,而不是再去訪問(wèn)單獨(dú)的鑒權(quán)服務(wù)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/weiBlog/p/9833807.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的.Net Core 商城微服务项目系列(二):使用Ocelot + Consul构建具备服务注册和发现功能的网关...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 梦到被猫抓伤脸是什么兆头
- 下一篇: [Matlab] 画图命令