.NET 微服务 Ocelot 网关实现方案

发布于:2025-09-03 ⋅ 阅读:(18) ⋅ 点赞:(0)

.NET微服务Ocelot网关实现方案在这里插入图片描述

Ocelot是.NET生态中常用的API网关,能够实现路由转发、负载均衡、限流和安全管控等核心功能。以下是一个完整的实现方案:

1. 项目配置

首先需要创建一个ASP.NET Core项目并安装Ocelot相关包:

Install-Package Ocelot
Install-Package Ocelot.Provider.Consul  # 如需服务发现
Install-Package Ocelot.Provider.Polly   # 如需熔断降级
2. 核心配置文件

创建ocelot.json配置文件,包含路由、负载均衡、限流和安全设置:

{
  "GlobalConfiguration": {
    "BaseUrl": "https://api.yourdomain.com",
    "RateLimitOptions": {
      "DisableRateLimitHeaders": false,
      "QuotaExceededMessage": "请求过于频繁,请稍后再试",
      "HttpStatusCode": 429,
      "ClientIdHeader": "ClientId"
    },
    "AuthenticationOptions": {
      "AuthenticationProviderKey": "GatewayAuth",
      "AllowedScopes": []
    }
  },
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/products/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "product-service-1",
          "Port": 5001
        },
        {
          "Host": "product-service-2",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/products/{everything}",
      "UpstreamHttpMethod": ["Get", "Post", "Put", "Delete"],
      
      // 负载均衡配置
      "LoadBalancerOptions": {
        "Type": "RoundRobin"  // 可选: RoundRobin, LeastConnection, NoLoadBalance
      },
      
      // 限流配置
      "RateLimitOptions": {
        "ClientWhitelist": [],
        "EnableRateLimiting": true,
        "Period": "1m",       // 时间窗口: 1s, 1m, 1h, 1d
        "PeriodTimespan": 30, // 重试等待时间(秒)
        "Limit": 100          // 时间窗口内最大请求数
      },
      
      // 认证授权
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "GatewayAuth",
        "AllowedScopes": ["product.read", "product.write"]
      },
      
      // 缓存配置
      "FileCacheOptions": {
        "TtlSeconds": 60,
        "Region": "products"
      }
    },
    {
      "DownstreamPathTemplate": "/api/orders/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "order-service",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/orders/{everything}",
      "UpstreamHttpMethod": ["Get", "Post"],
      
      "LoadBalancerOptions": {
        "Type": "LeastConnection"
      },
      
      "RateLimitOptions": {
        "EnableRateLimiting": true,
        "Period": "1m",
        "Limit": 50
      },
      
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "GatewayAuth",
        "AllowedScopes": ["order.read", "order.write"]
      }
    }
  ]
}

3. 服务启动配置

Program.cs中配置Ocelot服务:

using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// 配置Ocelot
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);

// 配置认证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer("GatewayAuth", options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"]))
        };
    });

// 配置跨域
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();

// 启用中间件
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
await app.UseOcelot();

app.Run();

4. 核心功能说明
  1. 路由转发

    • 通过UpstreamPathTemplateDownstreamPathTemplate映射API路径
    • 支持路径参数传递(如{everything}捕获所有后续路径)
    • 可根据HTTP方法限制访问(UpstreamHttpMethod
  2. 负载均衡

    • 支持三种负载均衡策略:
      • RoundRobin:轮询分配请求
      • LeastConnection:优先分配到连接数最少的服务
      • NoLoadBalance:总是使用第一个服务实例
    • 只需配置多个DownstreamHostAndPorts即可实现
  3. 限流控制

    • 基于时间窗口的限流(如1分钟内最多100次请求)
    • 支持自定义限流提示信息和HTTP状态码
    • 可配置白名单绕过限流
  4. 安全管控

    • 集成JWT认证,集中验证所有微服务的访问令牌
    • 基于Scope的权限控制(AllowedScopes
    • 统一处理跨域请求(CORS)
  5. 额外功能

    • 响应缓存(FileCacheOptions
    • 可扩展服务发现(如Consul)
    • 熔断降级(通过Polly集成)
5. 扩展建议
  • 结合Consul实现服务自动发现,无需手动配置服务地址
  • 使用Polly添加熔断和重试机制,提高系统弹性
  • 集成日志系统(如Serilog)记录网关访问日志
  • 实现自定义中间件处理特殊业务需求
  • 考虑添加请求/响应转换功能处理不同服务间的数据格式差异

通过以上配置,Ocelot网关可以为.NET微服务架构提供统一的入口,简化客户端调用,并增强系统的安全性和可扩展性。


网站公告

今日签到

点亮在社区的每一天
去签到