Rabbit.Common.RateLimit
1.2.0
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package Rabbit.Common.RateLimit --version 1.2.0
NuGet\Install-Package Rabbit.Common.RateLimit -Version 1.2.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Rabbit.Common.RateLimit" Version="1.2.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Rabbit.Common.RateLimit" Version="1.2.0" />
<PackageReference Include="Rabbit.Common.RateLimit" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Rabbit.Common.RateLimit --version 1.2.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Rabbit.Common.RateLimit, 1.2.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Rabbit.Common.RateLimit@1.2.0
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Rabbit.Common.RateLimit&version=1.2.0
#tool nuget:?package=Rabbit.Common.RateLimit&version=1.2.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Rabbit.Common.RateLimit
限流组件,支持令牌桶和滑动窗口算法。
安装
dotnet add package Rabbit.Common.RateLimit
依赖
- Rabbit.Common.Lite
- Rabbit.Common.Redis(可选,用于分布式限流)
- FreeRedis(可选,用于 Redis 存储)
功能
- 令牌桶算法: 平滑限流,支持突发流量
- 滑动窗口算法: 精确计数
- Redis 存储: 分布式限流支持
使用方式
Console 项目
using Microsoft.Extensions.DependencyInjection;
using Rabbit.Common.RateLimit;
// 1. 创建 DI 容器
var services = new ServiceCollection();
// 2. 注册限流服务
// 内存存储(单机)
services.AddRateLimitConfigure();
// Redis 存储(需先注册 Redis)
// services.AddFreeRedisConfigure("127.0.0.1:6379");
// services.AddRateLimitConfigure(RateLimitStorageType.Redis);
// 3. 构建服务提供者
var provider = services.BuildServiceProvider();
// 4. 使用限流
var rateLimitStore = provider.GetRequiredService<IRateLimitStore>();
var options = new RateLimitOptions {
Capacity = 100,
RefillPerSecond = 10
};
bool allowed = await rateLimitStore.IsAllowedAsync(
"user:123",
options,
AlgorithmEnum.TokenBucket
);
Web API 项目
using Rabbit.Common.RateLimit;
// 内存存储(单机)
services.AddRateLimitConfigure();
// Redis 存储(单实例)
services.AddRateLimitConfigure(RateLimitStorageType.Redis);
// Redis 存储(多实例)
services.AddFreeRedisMapConfigure("RateLimitRedis", "127.0.0.1:6379");
services.AddRateLimitConfigure(RateLimitStorageType.Redis, "RateLimitRedis");
使用静态方法
如果需要使用 RateLimitHelper 静态方法,在应用启动后初始化:
var app = builder.Build();
// 初始化静态 Helper
RateLimitHelper.Initialize(app.Services);
app.Run();
// 方式一:完整参数
var allowed = await RateLimitHelper.IsAllowedAsync(
key: userId,
options: new RateLimitOptions { Capacity = 100, RefillPerSecond = 10 },
algorithm: AlgorithmEnum.TokenBucket
);
// 方式二:令牌桶快捷方法
var allowed = await RateLimitHelper.IsAllowedAsync(userId, capacity: 100, refillPerSecond: 10);
// 方式三:滑动窗口快捷方法
var allowed = await RateLimitHelper.IsAllowedWindowAsync(userId, capacity: 5, window: TimeSpan.FromMinutes(1));
使用中间件
app.Use(async (context, next) =>
{
var store = context.RequestServices.GetRequiredService<IRateLimitStore>();
// 按 IP 限流
var key = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
var options = new RateLimitOptions
{
Capacity = 100,
RefillPerSecond = 10,
Window = TimeSpan.FromSeconds(1),
Prefix = "rl:api:"
};
if (!await store.IsAllowedAsync(key, options, AlgorithmEnum.TokenBucket))
{
context.Response.StatusCode = 429;
await context.Response.WriteAsync("请求过于频繁,请稍后重试");
return;
}
await next();
});
不同场景限流
// API 限流 - 令牌桶(允许突发)
var apiOptions = new RateLimitOptions
{
Capacity = 100,
RefillPerSecond = 10,
Prefix = "rl:api:"
};
// 登录限流 - 滑动窗口(严格计数)
var loginOptions = new RateLimitOptions
{
Capacity = 5,
Window = TimeSpan.FromMinutes(1),
Prefix = "rl:login:"
};
if (!await store.IsAllowedAsync(userId, loginOptions, AlgorithmEnum.SlidingWindow))
{
return "登录次数过多,请稍后再试";
}
配置选项
public class RateLimitOptions
{
/// <summary>
/// 令牌桶容量 / 窗口最大请求数
/// </summary>
public int Capacity { get; set; }
/// <summary>
/// 每秒填充速率(仅令牌桶用)
/// </summary>
public int RefillPerSecond { get; set; }
/// <summary>
/// 时间窗口
/// </summary>
public TimeSpan Window { get; set; } = TimeSpan.FromSeconds(1);
/// <summary>
/// 键前缀
/// </summary>
public string Prefix { get; set; } = "rl:";
}
算法对比
| 算法 | 特点 | 适用场景 |
|---|---|---|
| TokenBucket | 允许突发,平滑限流 | 普通 API |
| SlidingWindow | 精确计数,严格限流 | 登录、支付 |
许可证
MIT
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net10.0
- Microsoft.Extensions.Options (>= 10.0.4)
- Rabbit.Common.Lite (>= 1.2.0)
- Rabbit.Common.Redis (>= 1.2.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Rabbit.Common.RateLimit:
| Package | Downloads |
|---|---|
|
Rabbit.Common.Full
Meta-package referencing all Rabbit.Common utility packages. / Rabbit.Common 全家桶,引用所有子包 |
GitHub repositories
This package is not used by any popular GitHub repositories.