Net Core 网关 Ocelot 简单案例
1、什么是Ocelot
Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器与Service Fabric、Butterfly Tracing集成。
2、前期准备工作
新建一个Web API,返回IP+Port字符串(有利于我们直观感受)
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace StudyGateway.Controllers { [ApiController] [Route("api/[controller]")] public class WeatherForecastController : ControllerBase { private IConfiguration _configuration; public WeatherForecastController(IConfiguration configuration) { this._configuration = configuration; } [HttpGet] public string Get() { string ip = _configuration["IP"]; string port = _configuration["Port"]; return $@"{ip} {port}"; } } }
CMD启动该站点
dotnet StudyGateway.dll --urls="http://*:5177" --ip="127.0.0.1" --port=5177
显示截图:
3、开始设计网关(Gateway)
创建一个新的Net Core Api项目,引用Ocelot包(注意版本对应 core 3.x 对应 Ocelot 15)
安装完成后,修改Startup,因为这个站点只是作为网关,所以只需要以下配置
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Ocelot.DependencyInjection; using Ocelot.Middleware; namespace MyOcelot { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddOcelot(new ConfigurationBuilder().AddJsonFile("configuration.json").Build()); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseOcelot(); } } }
新增一个configuration.json,作为Ocelot的配置文件(记得修改 [复制到输出目录])
配置下游站点
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "127.0.0.1", "Port": 5177 } ], "UpstreamPathTemplate": "/GateWay/{url}", //这个url会转到上面的url "UpstreamHttpMethod": [ "Get", "POST" ] } ], "GlobalConfiguration": { "RequestIdKey": "OcRequestId", "AdministrationPath": "/administration" } }
启动项目,访问
成功转载!!!
4、负载均衡策略
前期准备工作的网站,通过CMD再启动一个新实例
dotnet StudyGateway.dll --urls="http://*:5178" --ip="127.0.0.1" --port=5178
修改Ocelot配置文件,新增一个下游站点
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "127.0.0.1", "Port": 5177 }, { "Host": "127.0.0.1", "Port": 5178 } ], "UpstreamPathTemplate": "/GateWay/{url}", //这个url会转到上面的url "UpstreamHttpMethod": [ "Get", "POST" ], "LoadBalancerOptions": { "Type": "RoundRobin" //负载均衡类型:轮询(其他类型也有,不一一列举了) } } ], "GlobalConfiguration": { "RequestIdKey": "OcRequestId", "AdministrationPath": "/administration" } }
重新生成,访问:
5、缓存策略
安装Nuget包:Ocelot.Cache.CacheManager
修改Ocelot配置文件,添加FileCacheOptions节点
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "127.0.0.1", "Port": 5177 }, { "Host": "127.0.0.1", "Port": 5178 } ], "UpstreamPathTemplate": "/GateWay/{url}", //这个url会转到上面的url "UpstreamHttpMethod": [ "Get", "POST" ], "LoadBalancerOptions": { "Type": "RoundRobin" //负载均衡类型:轮询(其他类型也有,不一一列举了) }, "FileCacheOptions": { "TtlSeconds": 3, "Region": "somename" } } ], "GlobalConfiguration": { "RequestIdKey": "OcRequestId", "AdministrationPath": "/administration" } }
刷新
http://localhost:57789/GateWay/weatherforecast
访问后会缓存地址3秒。
比如:第一次访问,转载到Port=5177,3秒内都会访问5177
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异