Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由、认证、鉴权、简单缓存、限流熔断、负载均衡器等。简单的来说Ocelot是一堆的asp.net core middleware组成的一个有顺序的管道。当它拿到请求之后会用一个request builder来构造一个HttpRequestMessage发到下游的真实服务器,等下游的服务返回response之后再由一个middleware将它返回的HttpResponseMessage映射到HttpResponse上。
项目描述
> 1. 这是一个ASP.NET Core Web项目,主要展示Ocelot的使用
> 2. 实现Ocelot来控制访问
> 3. 实现Ocelot来控制负载均衡
项目架构
// OcelotStudy项目 namespace OcelotInput { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("ocelotsettings.json", true, true) .AddEnvironmentVariables(); }) .UseStartup<Startup>(); } } namespace OcelotInput { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddOcelot(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseOcelot().Wait(); } } }
其他两个是asp.net core api的项目,vs直接创建就可以
Ocelot配置
{ "ReRoutes": [ { "DownstreamPathTemplate": "/values/{action}", //下游服务配置 "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 54679 }, { "Host": "localhost", "Port": 57417 } ], "UpstreamPathTemplate": "/values/{action}", //上游服务配置 "UpstreamHttpMethod": [ "Get" ], //"AddHeadersToRequest": {}, //"AddClaimsToRequest": {}, //"RouteClaimsRequirement": {}, //配置Claims鉴权 //"AddQueriesToRequest": {}, //"RequestIdKey": "", //"FileCacheOptions": { //缓存配置 // "TtlSeconds": 0, // "Region": "" //}, //"ReRouteIsCaseSensitive": false, //"ServiceName": "", //"QoSOptions": { //服务质量与熔断 // "ExceptionsAllowedBeforeBreaking": 3, // "DurationOfBreak": 10, // "TimeoutValue": 5000 //}, "LoadBalancerOptions": { "Type": "LeastConnection" } //LoadBalancer将决定负载均衡的算法,LeastConnection – 将请求发往最空闲的那个服务器,RoundRobin – 轮流发送,NoLoadBalance – 总是发往第一个请求或者是服务发现 //"RateLimitOptions": { //为限流配置 // "ClientWhitelist": [], // "EnableRateLimiting": false, // "Period": "", // "PeriodTimespan": 0, // "Limit": 0 //}, //"AuthenticationOptions": { //配置服务认证 // "AuthenticationProviderKey": "", // "AllowedScopes": [] //}, //"HttpHandlerOptions": { // "AllowAutoRedirect": false, // "UseCookieContainer": false // //"UseTracing": true //} //"UseServiceDiscovery": false, // 配置服务发现 } //{ // "DownstreamPathTemplate": "/{url}", // "DownstreamScheme": "https", // "DownstreamHostAndPorts": [ // { // "Host": "localhost", // "Port": 80 // } // ], // "UpstreamPathTemplate": "/{url}", // "UpstreamHttpMethod": [ "Get" ] //} ] //"Aggregates": [ //服务聚合配置 // { // "ReRouteKeys": [ // "Tom", // "Laura" // ], // "UpstreamPathTemplate": "/" // } //] }
运行效果
Web1项目:http://localhost:54679, Web2项目:http://localhost:57417, Ocelot项目:http://localhost:57083
源码地址
https://github.com/jasonhua95/samll-project/tree/master/OcelotStudy