asp.net 如何实现分页缓存HOT巧克力?

vmdwslir  于 6个月前  发布在  .NET
关注(0)|答案(1)|浏览(86)

所以我想实现缓存。我使用的是版本11 hc。现在每次分页发生时都会有请求发送到数据库。我想实现它,以便第一次发出请求时,所有数据都被检索和缓存,并且随后的请求(转到下一页或上一页)从缓存中检索。如何开始?

pieyvz9o

pieyvz9o1#

刚刚实施了这个解决方案,似乎它对我很好。希望它仍然是相关的。
中间件类本身:

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));
        }
    }
}

字符串
请注意,缓存服务只是默认Redis IDataBase接口的 Package 器,因此您可以根据需要实现它。
然后在你的program.cs或任何你的DI逻辑中:

services.AddGraphQLServer()
            .AddQueryType<ArtistsQL>()
            .AddProjections()
            .AddSorting()
            .AddFiltering()
            .AddAuthorization()
            //request pipeline starts
            .UseInstrumentation()
            .UseExceptions()
            .UseTimeout()
            .UseDocumentCache()
            .UseDocumentParser()
            .UseDocumentValidation()
            .UseRequest<CachingMiddleware>()
            .UseOperationCache()
            .UseOperationComplexityAnalyzer()
            .UseOperationResolver()
            .UseOperationVariableCoercion()
            .UseOperationExecution();


每个以“Use”开头的方法(除了WASHRequest)都来自热巧克力中的默认请求管道。
注意方法的顺序很重要,在修改之前要三思而后行。我也不确定CachingMiddleware的位置,所以如果你认为它应该在其他地方,请在评论中告诉我。
下面是我的示例查询:

public class ArtistsQL
{
    [UsePaging(IncludeTotalCount = true)]
    [UseProjection]
    [UseFiltering]
    [UseSorting]
    // [Authorize(Role.RoleNames.Default)]
    public async Task<IQueryable<Artist>> GetArtists([Service(ServiceKind.Resolver)] IApplicationDbContext context)
    {
        return context.Artists;
    }
}


如果想了解更多信息,请查看:Guide about hot chocolate middlewares

相关问题