项目地址
思路
- 固定属性作为缓存的key(用户id、ip...)
- 缓存请求的时间
- 框架依赖抽象
定义框架接口
public interface ILimiting
{
Task<bool> CheckIdentityLimited(string identity);
}
Redis注入一下
public void ConfigureServices(IServiceCollection services)
{
var redis = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis"));
services.AddSingleton(redis.GetDatabase())
}
定义配置类
public class LimitingOptions
{
public LimitingOptions()
{
Limit = 10;
Time = TimeSpan.FromSeconds(60);
Allows = Array.Empty<string>();
CallbackDelegate = new(async ctx =>
{
ctx.Response.StatusCode = 503;
ctx.Response.ContentType = "application/json;charset=utf-8";
var json = "{\"message\":\"访问太快了,休息一下吧\"}";
await ctx.Response.WriteAsync(json);
});
IdentityDelegate = new(ctx =>
{
return ctx.Request.HttpContext
.Connection.RemoteIpAddress.MapToIPv4().ToString();
});
}
//约定次数
public int Limit { get; set; }
//约定时间
public TimeSpan Time { get; set; }
//白名单
public IEnumerable<string> Allows { get; set; }
//限流后的回调
public Action<HttpContext> CallbackDelegate { get; set; }
//设置限流的键
public Func<HttpContext, string> IdentityDelegate { get; set; }
}
- 上面的默认配置解读:60秒内访问超过10次将被限流
实现Redis限流服务
public class RedisCatchLimiting : ILimiting
{
private readonly IDatabase _db;
private readonly LimitingOptions _options;
public RedisCatchLimiting(IDatabase db, LimitingOptions options)
{
_db = db;
_options = options;
}
public async Task<bool> CheckIdentityLimited(string identity)
{
if (_options.Allows.Contains(key))
return false;
//把已缓存的所有时间查出来
var items = _db
.ListRange(key)
.Select(x => DateTime.Parse(x.ToString()))
.ToList();
items.Add(DateTime.Now);
//算出约定时间
var timeout = DateTime.Now.AddSeconds(-_options.Time.TotalSeconds);
//如果访问的频率超出限制,下一步操作
if (items.Count(x => x >= timeout) > _options.Limit)
return true;
//使用缓存集合 当前时间作为value
await _db.ListRightPushAsync(key, DateTime.Now.ToString());
//删掉不在时间范围的item
foreach (var item in items.Where(x => x < timeout))
{
_db.ListRemove(key, item.ToString());
}
return false;
}
}
实现MemoryCatch限流服务
public class MemoryCatchLimiting : ILimiting
{
private readonly IMemoryCache _db;
private readonly LimitingOptions _options;
public MemoryCatchLimiting(IMemoryCache db,
LimitingOptions options)
{
_db = db;
_options = options;
}
public Task<bool> CheckIdentityLimited(string identity)
{
//白名单永远不会被限流
if (_options.Allows.Contains(identity))
return Task.FromResult(false);
//把这个键的访问记录拿出来
_db.TryGetValue(ip, out List<DateTime> items);
//防止null引用
items ??= new();
//这次访问的时间加进去
items.Add(DateTime.Now);
//算出时间范围
var timeout = DateTime.Now.AddSeconds(-_options.Seconds);
//删除不在时间范围的item
items.RemoveAll(x => x < timeout);
//如果访问的次数超出了约定 该ip检查为被限流
if (items.Count > _options.Limit)
return Task.FromResult(true);
//结果重新缓存
_db.Set(ip, items);
return Task.FromResult(false);
}
}
服务注册扩展
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddRedisCatchLimiting(this IServiceCollection services,
Action<LimitingOptions> optionsAction = null)
{
var options = new LimitingOptions();
optionsAction?.Invoke(options);
services.AddSingleton(_ => options);
services.AddSingleton<ILimiting, RedisCatchLimiting>();
return services;
}
public static IServiceCollection AddMemoryCatchLimiting(this IServiceCollection services,
Action<LimitingOptions> optionsAction = null)
{
var options = new LimitingOptions();
optionsAction?.Invoke(options);
services.AddSingleton(_ => options);
services.AddSingleton<ILimiting, MemoryCatchLimiting>();
return services;
}
}
写一个限流中间件
public class LimitingMiddleWare
{
private readonly RequestDelegate _next;
private readonly ILimiting _limiting;
private readonly LimitingOptions _options;
public LimitingMiddleWare(
RequestDelegate next,
ILimiting limiting,
LimitingOptions options)
{
_next = next;
_limiting = limiting;
_options = options;
}
public async Task Invoke(HttpContext context)
{
//拿出建
var identity = _options.IdentityDelegate.Invoke(context);
//检查建是否被限流
var result = await _limiting.CheckIdentityLimited(identity);
if (result)
{
//如果用户限流调用限流回调
_options.CallbackDelegate.Invoke(context);
}
else
{
//否则下一步
await _next.Invoke(context);
}
}
}
中间件扩展
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseLimiting(this IApplicationBuilder app)
{
//将中间件加入到管道模型中
return app.UseMiddleware<LimitingMiddleWare>();
}
}
StartUp中使用
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache()
.AddMemoryCatchLimiting();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseLimiting();
}
public void ConfigureServices(IServiceCollection services)
{
//services.AddMemoryCache()
// .AddMemoryCatchLimiting();
var redis = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis"));
services.AddSingleton(redis.GetDatabase())
.AddRedisCatchLimiting(o =>
{
//限制次数
o.Limit = 5;
//约定时间
o.Time = TimeSpan.FromSeconds(10);
//设置唯一标识的委托
o.IdentityDelegate = context =>
{
//自定义返回唯一键
//return context.User.Claims...
//return context.Request.Cookies...
return context.Request.HttpContext
.Connection.RemoteIpAddress.MapToIPv4().ToString();
};
//回调委托
o.CallbackDelegate = async context =>
{
context.Response.StatusCode = 503;
string s = "哈哈哈,被限流了!";
await context.Response.WriteAsync(s);
};
//白名单
o.Allows = new string[]
{
"0.0.0.1"
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseLimiting();
}
- 随便来个控制器试试(这里就不演示了)
- 或者把路由也做到配置中?
- 马上下班了^ ^