一夫当关万夫莫开
一:源起:
当我们的应用不再是单体架构时,微服务将原先单体下的功能组件分割后,产生了许多个微服务,实际上我们还是以前那样的操作,访问服务接口,达到我们的目的,而这次不过是换成了http(s)请求的微服务,以前的服务接口也是有base服务以便挂载一些通用处理,所以这里分化出去的微服务也是要一个统一的入口或者称之为管家的东西来管理与分发。那么API网关这样一个概念就呼之欲出了,这里将记录.net core开源的网关 Ocelot 的使用。
二:搬砖:
此处流程只是Ocelot作为网关转发请求的简单demo,代码设置源自网上,部分自己瞎改
环境:
vs2017 || .net core 2.0 || Ocelot 8.0.0
1.创建网关api(nuget或者其他引入Ocelot的依赖),以及2个微服务api。
2.网关api这里我省去了原有的(control以及mvc服务)
Ocelot配置文件
{ "ReRoutes": [ //微服务一配置: { "DownstreamPathTemplate": "/api/get", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 60001 } ], "UpstreamPathTemplate": "/api/get", "UpstreamHttpMethod": [ "Get" ] }, //微服务二配置: { "DownstreamPathTemplate": "/api/post", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 60002 } ], "UpstreamPathTemplate": "/api/post", "UpstreamHttpMethod": [ "Get" ] } ], "GlobalConfiguration": { "BaseUrl": "localhost:60000" } }
网关api设置:
在 Program.cs添加Ocelot的配置文件
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) //此处添加Ocelot的配置 .ConfigureAppConfiguration((hostingContext, builder) => { builder .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("ocelot.json"); }) .UseStartup<Startup>() .Build();
在Startup.cs添加Ocelot服务
public void ConfigureServices(IServiceCollection services) { //添加网关配置 services.AddOcelot(Configuration); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseOcelot().Wait(); }
2个微服务就是普通的设置:
namespace MicroServicePost.Controllers { [Route("api/[controller]")] public class PostController : Controller { [HttpGet] public IEnumerable<string> yishuiPost() { return new string[] { "易", "水", "POST" }; } } }
这里是调试启动3个进程,且Ocelot的配置需要明确的地址,所以端口要么是看api各自属性里面设定的要么就是统一改下占用端口,且调试启动3个端口需要到解决方案属性那里设定,且这3个进程同属于一个解决方案内,后续的部署将是启动docker而不是这样图方便一个解决方案启动的方式。
运行结果如下:
当往网关输入对应的微服务路由时,你能看到不同服务的回调,当然实际上微服务端口还是需要禁止访问的,对外面只是暴露80端口这个就是后话了。