You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在K8s多副本YARP网关中实现基于分布式缓存的全局限流?

YARP分布式全局限流配置方案
  • 步骤1:安装依赖包
    如果使用Redis作为分布式缓存(K8s环境中最常用的选择),执行以下命令安装所需NuGet包:

    dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
    dotnet add package Microsoft.AspNetCore.RateLimiting
    
  • 步骤2:注册分布式缓存服务
    在Program.cs中添加Redis缓存的注册配置,替换为你的Redis连接信息:

    builder.Services.AddStackExchangeRedisCache(options =>
    {
        // 从配置文件读取Redis连接字符串,推荐做法
        options.Configuration = builder.Configuration.GetConnectionString("Redis");
        // 给缓存键添加前缀,避免与其他服务缓存冲突
        options.InstanceName = "YARP-RateLimiter-";
    });
    
  • 步骤3:修改限流配置为分布式版本
    将原来的内存限流策略替换为分布式固定窗口限流,并指定使用分布式缓存存储限流状态:

    builder.Services.AddRateLimiter(rateLimiterOptions =>
    {
        rateLimiterOptions.AddDistributedFixedWindowLimiter(
            policyName: "FixedRateLimiter", 
            options =>
            {
                options.Window = TimeSpan.FromSeconds(12);
                options.PermitLimit = 4;
                options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
                options.QueueLimit = 2;
            });
    
        // 启用分布式缓存作为限流状态存储
        rateLimiterOptions.UseDistributedCache();
        // 确保限流中间件被加载
        rateLimiterOptions.RequireRateLimitingMiddleware();
    });
    
  • 步骤4:在YARP路由中绑定限流策略
    在YARP的路由配置(如appsettings.json)中,给目标路由关联限流策略:

    "ReverseProxy": {
        "Routes": {
            "sampleRoute": {
                "ClusterId": "sampleCluster",
                "Match": {
                    "Path": "/{**catch-all}"
                },
                "RateLimiterPolicy": "FixedRateLimiter" // 绑定之前定义的限流策略
            }
        },
        "Clusters": {
            "sampleCluster": {
                "Destinations": {
                    "sampleDestination": {
                        "Address": "https://example.com/"
                    }
                }
            }
        }
    }
    
  • 关键注意事项

    • 确保K8s集群内所有YARP副本都能访问到Redis服务,建议通过K8s Service暴露Redis,使用内部域名连接。
    • 必须使用.NET 7或更高版本,分布式限流是.NET 7新增的特性。
    • 若需替换其他分布式缓存(如SQL Server、NCache等),只需更换对应的IDistributedCache注册代码即可。

内容的提问来源于stack exchange,提问作者Ehsan Akbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 09:02:12