internal sealed class CachingMiddleware
{
private readonly RequestDelegate _next;
public CachingMiddleware(
RequestDelegate next)
{
_next = next ??
throw new ArgumentNullException(nameof(next));
}
public async ValueTask InvokeAsync(IRequestContext context, [Service] ICacheService cache)
{
var key = context.Document.ToString();
var res = await cache.GetDataAsync<Dictionary<string, object?>?>(key);
var isCached = res is not null;
if (isCached)
{
context.Result = new QueryResult(res);
}
await _next(context).ConfigureAwait(false);
if (!isCached)
{
var toCache = ((QueryResult)context.Result).Data;
await cache.SetDataAsync(key, toCache, DateTimeOffset.UtcNow.AddSeconds(30));
}
}
}
1条答案
按热度按时间pieyvz9o1#
刚刚实施了这个解决方案,似乎它对我很好。希望它仍然是相关的。
中间件类本身:
字符串
请注意,缓存服务只是默认Redis IDataBase接口的 Package 器,因此您可以根据需要实现它。
然后在你的program.cs或任何你的DI逻辑中:
型
每个以“Use”开头的方法(除了WASHRequest)都来自热巧克力中的默认请求管道。
注意方法的顺序很重要,在修改之前要三思而后行。我也不确定CachingMiddleware的位置,所以如果你认为它应该在其他地方,请在评论中告诉我。
下面是我的示例查询:
型
如果想了解更多信息,请查看:Guide about hot chocolate middlewares