🚪 网关

微服务API管理:构建统一的API网关

深入探讨微服务API管理策略,包括API网关设计、限流熔断、认证授权、监控分析等核心功能

一、API管理概述

API管理是微服务架构中的关键组件,负责统一管理所有对外API。

二、API网关设计

API网关作为所有请求的入口,提供路由、认证、限流等功能。

// Ocelot 完整配置示例
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/products/{id}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        { "Host": "product-service", "Port": 80 }
      ],
      "UpstreamPathTemplate": "/products/{id}",
      "UpstreamHttpMethod": [ "Get" ],
      "RateLimitOptions": {
        "ClientWhitelist": [],
        "EnableRateLimiting": true,
        "Period": "1m",
        "PeriodTimespan": 10,
        "Limit": 100
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://api.example.com"
  }
}

三、API认证与授权

实现统一的API安全控制。

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IConfiguration _config;

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue("X-API-Key", out var apiKey))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await context.Response.WriteAsync("API Key missing");
            return;
        }

        var validApiKey = _config["ApiSettings:ApiKey"];
        if (!apiKey.Equals(validApiKey))
        {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            await context.Response.WriteAsync("Invalid API Key");
            return;
        }

        await _next(context);
    }
}

四、限流与熔断策略

保护后端服务免受过载影响。

五、API版本管理

管理API的多个版本。

// 版本路由配置
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/v1/products",
      "UpstreamPathTemplate": "/v1/products"
    },
    {
      "DownstreamPathTemplate": "/api/v2/products",
      "UpstreamPathTemplate": "/v2/products"
    }
  ]
}

六、API文档与SDK生成

自动生成API文档和客户端SDK。

七、API监控与分析

收集和分析API使用数据。

public class ApiMetricsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMetrics _metrics;

    public async Task InvokeAsync(HttpContext context)
    {
        var sw = Stopwatch.StartNew();
        try
        {
            await _next(context);
        }
        finally
        {
            sw.Stop();
            _metrics.RecordRequestDuration(context.Request.Path, sw.Elapsed);
            _metrics.RecordStatusCode(context.Response.StatusCode);
        }
    }
}

八、API安全防护

防止常见的API攻击。

九、API生命周期管理

管理API从设计到废弃的完整生命周期。

十、API管理工具对比

比较Ocelot、Kong、Apigee等API管理工具。