一、概要
Ocelot是.Net Core下一个开源API网关;Ocelot主要目标是在.NET在微服务或面向服务架构中提供统一的入口服务,
Ocelot拿到HttpRequest对象到管道后,先创建HttpRequestMessage对象,该对象用于向下游服务发出请求。再将HttpResponseMessage映射到HttpResponse对象上,并返回给客户端。。
主要功能:统一入口、认证、鉴权、限流熔断、内置了负载均衡等等
二、单网关QuickStart
2.1 API网关
新建.Net Core 2.0 webapi项目:Practice.ApiGetway
添加Ocelot的Nuget包引用到该项目:Install-Package Ocelot
修改Startup.cs:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddOcelot(new ConfigurationBuilder().AddJsonFile("ocelot_config.json").Build()); } // 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().Wait(); app.UseMvc(); } }
修改Program.cs:
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseKestrel() .UseUrls("http://*:5000") .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); }
添加一个json文件ocelot_config.json,设置属性:始终复制
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/users", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5001 } ], "UpstreamPathTemplate": "/users/values", "UpstreamHttpMethod": [ "Get" ], "QoSOptions": { "ExceptionsAllowedBeforeBreaking": 3, "DurationOfBreak": 10, "TimeoutValue": 5000 } }, { "DownstreamPathTemplate": "/api/news", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5002 } ], "UpstreamPathTemplate": "/news/values", "UpstreamHttpMethod": [ "Get" ], "QoSOptions": { "ExceptionsAllowedBeforeBreaking": 3, "DurationOfBreak": 10, "TimeoutValue": 5000 } } ], "GlobalConfiguration": { //"BaseUrl": "https://api.mybusiness.com" } }
修改launchSettings.json设置个固定的端口
2.2 下游实际API
最后在新建两个API项目:
项目:Practice.NewsApi 、Controller:UsersController、端口:5002
项目:Practice.UsersApi 、Controller:NewsController、端口:5001
运行三个项目
不再截图,运行结果:
访问网关:http://localhost:5000/users/values 会得到 http://localhost:5001/api/users 结果
访问网关:http://localhost:5000/news/values 会得到 http://localhost:5002/api/news 结果
资源:
项目开源地址:https://github.com/ThreeMammals/Ocelot
官方文档:http://ocelot.readthedocs.io/en/latest/
资源:https://github.com/geffzhang/awesome-ocelot
博客:
http://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html