Ocelot是基于.NET Core构建的开源API网关解决方案,提供路由管理、请求聚合、服务发现、身份验证、授权控制、限流熔断等核心功能,同时支持与Service Fabric和Butterfly Tracing的深度集成。所有功能均通过简洁的JSON配置即可启用,无需复杂编码。
API网关作为系统对外的统一入口,负责请求路由、安全控制、负载均衡等关键任务。Ocelot通过ASP.NET Core中间件管道处理请求:将上游请求转换为下游服务的HttpRequestMessage,处理响应后再返回给客户端。
基本使用时,网关服务通过JSON配置文件定义路由规则。客户端请求到达网关后,根据配置转发至对应的下游服务。例如,将路径/blog/{articleId}映射到下游服务的/api/articles/{articleId}。
集成Identity Server时,网关会验证JWT令牌的有效性,并根据配置的权限范围执行授权检查。
为避免单点故障,可部署多个Ocelot实例,配合负载均衡器实现高可用性。
结合Consul作为服务注册中心,Ocelot可动态管理下游服务实例,实现自动健康检查和动态路由。
通过NuGet安装Ocelot组件:
dotnet add package Ocelot
配置文件示例:
{
"ReRoutes": [],
"GlobalConfiguration": {
"BaseUrl": "https://api.example.com"
}
}
其中GlobalConfiguration的BaseUrl定义网关对外暴露的域名,例如当网关部署在Nginx代理后,此处应填写代理的域名。
在WebHostBuilder中加载配置文件:
public static IWebHost CreateHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
config.SetBasePath(context.HostingEnvironment.ContentRootPath)
.AddJsonFile("ocelot.json");
})
.UseStartup()
.Build();
}
Startup类中添加依赖注入和中间件:
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
}
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();
}
Ocelot的核心功能通过路由配置实现,每个路由包含上游和下游的映射规则。以下是一个基础路由配置示例:
{
"DownstreamPathTemplate": "/api/v1/users/{userId}",
"UpstreamPathTemplate": "/users/{userId}",
"DownstreamHostAndPorts": [
{ "Host": "user-service", "Port": 8080 }
],
"UpstreamHttpMethod": [ "GET" ]
}
- DownstreamPathTemplate:下游服务的路径模板
- UpstreamPathTemplate:客户端请求的路径模板
- DownstreamHostAndPorts:下游服务的地址列表
- UpstreamHttpMethod:允许的HTTP方法
通配符路由配置示例:
{
"DownstreamPathTemplate": "/{url}",
"DownstreamHostAndPorts": [
{ "Host": "backend.example.com", "Port": 443 }
],
"UpstreamPathTemplate": "/{url}",
"UpstreamHttpMethod": [ "GET" ]
}
通配符路由优先级最低,其他路由规则会优先匹配。
路由负载均衡配置:
{
"DownstreamPathTemplate": "/products/{id}",
"DownstreamHostAndPorts": [
{ "Host": "prod-svc-01", "Port": 5000 },
{ "Host": "prod-svc-02", "Port": 5000 }
],
"LoadBalancer": "RoundRobin",
"UpstreamPathTemplate": "/products/{id}",
"UpstreamHttpMethod": [ "GET" ]
}
LoadBalancer支持LeastConnection、RoundRobin和NoLoadBalance策略。
请求聚合功能将多个API响应合并为一个:
{
"ReRoutes": [
{
"Key": "ProductService",
"DownstreamPathTemplate": "/products",
"UpstreamPathTemplate": "/product-api",
"UpstreamHttpMethod": [ "GET" ]
},
{
"Key": "UserService",
"DownstreamPathTemplate": "/users",
"UpstreamPathTemplate": "/user-api",
"UpstreamHttpMethod": [ "GET" ]
}
],
"Aggregates": [
{
"ReRouteKeys": [ "ProductService", "UserService" ],
"UpstreamPathTemplate": "/combined"
}
]
}
访问/combined时,返回合并后的JSON数据。
限流配置示例:
"RateLimitOptions": {
"EnableRateLimiting": true,
"Period": "1m",
"Limit": 100,
"QuotaExceededMessage": "请求频率超出限制"
}
熔断配置:
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 5,
"DurationOfBreak": 30,
"TimeoutValue": 5000
}
缓存配置:
"FileCacheOptions": {
"TtlSeconds": 60,
"Region": "product-cache"
}
JWT认证配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer("AuthKey", options =>
{
options.Authority = "https://auth.example.com";
options.Audience = "api";
});
}
路由配置中启用认证:
"AuthenticationOptions": {
"AuthenticationProviderKey": "AuthKey",
"AllowedScopes": [ "read", "write" ]
}
鉴权配置:
"RouteClaimsRequirement": {
"role": "admin"
}
请求头转化示例:
"UpstreamHeaderTransform": {
"X-Custom-Header": "old-value, new-value"
},
"DownstreamHeaderTransform": {
"Location": "{BaseUrl}/redirect"
}
Claims转化示例:
"AddClaimsToRequest": {
"UserId": "Claims[identity] > value[1] > :"
}
Consul服务发现功能需结合Consul配置,详情请参考相关文档。