当前位置:网站首页>.NET7之MiniAPI(特别篇) :Preview6 缓存和限流
.NET7之MiniAPI(特别篇) :Preview6 缓存和限流
2022-07-16 00:33:00 【dotNET跨平台】
前几在用MiniAPI时还想没有比较优雅的缓存,这不,Preivew6就带来了。使用起来很简单,注入Sevice,引用中间件,然后在Map方法的后面跟CacheOutput()就ok了,CacheOutpu也有不同的参数,可以根据每个方法定制,当然也可以有全局配置,在添加Service时进行统一配置。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache();
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/cached", () => DateTime.Now.ToString()).CacheOutput();
app.MapGet("/query", () => DateTime.Now.ToString()).CacheOutput(p => p.VaryByQuery("key").Expire(TimeSpan.FromMinutes(10)));
app.Run();本次Preview,还优化了限流,引入了TokenBucketLimiter,还优化了RateLimiterOptions中的属性。我们通过一个例子来看一下TokenBucketLimiter.
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var limiterName = "MyLimiterName";
//间隔多少时间补发
var options = new RateLimiterOptions().AddTokenBucketLimiter(limiterName, new TokenBucketRateLimiterOptions(1, QueueProcessingOrder.OldestFirst, 1, TimeSpan.FromSeconds(8), 1));
app.UseRateLimiter(options);
app.MapGet("/limit", () =>
{
app.Logger.LogInformation($"limit 开始 {DateTime.Now}");
Thread.Sleep(5000);
app.Logger.LogInformation($"limit 结束 {DateTime.Now}");
return DateTime.Now.ToString();
}).RequireRateLimiting(limiterName);
app.Run();在构建Options时,有一个参数,TimeSpan,它是当等待的请求,与上一个请求开始之间的时间间隔,即等待多长时间开始。看结果,两个请求,红色的是间隔我们设的8s,后台的两个开始也是间隔8s,虽然第一个请求已于3s前返回,但第二个请求还是要等待的。

边栏推荐
猜你喜欢

【C语言】结构体、枚举、联合体

Forco:全球首发,暴力增值,年度最佳币圈风口

Memory management: memory allocation and recycling

jol-core

mysql报错 1142 - SELECT command denied to user ‘dev‘@‘localhost‘ for table ‘user‘ (已解决)

【MySql项目实战优化】通过执行计划分析追加索引

无线通信安全作业4

ThinkPHP 3 adds word segmentation weight search function and phpanalysis plug-in

jol-core

Flink (III) processing function
随机推荐
WINFORM + C# GDI+编程实现Photoshop, Illustrator类似绘图工具箱
[stroll and brush questions] - reverse order string II
【vulnhub】DC9
免费SSL证书申请及部署实践
网络安全服务国家战略需要
Quweihai: insisting on choosing and not giving up is the magic weapon to realize the original intention
2022年全国最新消防设施操作员(初级消防设施操作员)模拟试题及答案
你认为科研道德方面有哪些坚决不能触碰的红线?
Redis概述、安装、可视化访问
How does the trend of banking situation in London come into being
C language preprocessing command [i]
Camera image quality debugging, learning materials sharing
Memory management: memory allocation and recycling
Meshlab之插件式开发
ThinkPHP 3 adds word segmentation weight search function and phpanalysis plug-in
【C语言】动态通讯录
flutter EventBus
Autojs script notes
[SQL interview question] find the number of users who have clicked three times in a row, and there can be no other people's clicks in the middle
What is the once brilliant streaming media protocol RTMP? Can it be completely replaced? Yiwen takes you into the world of RTMP