کش کردن کوئری ها با استفاده از کتابخانه MediatR
نویسنده: عثمان رحیمی
تاریخ: ۱۴۰۰/۱۱/۲۸ ۶:۵۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public interface ICachableQuery
{
public string Key { get;}
} public class GetBookmarkQuery : IRequest<BookmarkDto>, ICachableQuer
{
public int Id { get; init; }
public string Key => $"{nameof(GetBookmarkQuery)}-{Id}";
public GetBookmarkQuery(int id)
{
Id = id;
}
} public class CachingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : ICachableQuer
{
private readonly IDistributedCache _cache;
public CachingBehavior(IDistributedCache distributedCache)
{
_cache = distributedCache;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
TResponse response;
var cachedResponse = await _cache.GetAsync(request.Key, cancellationToken);
if (cachedResponse != null)
response = JsonConvert.DeserializeObject<TResponse>(Encoding.Default.GetString(cachedResponse));
else
{
response = await next();
var serialized = Encoding.Default.GetBytes(JsonConvert.SerializeObject(response));
await _cache.SetAsync(request.Key, serialized, cancellationToken);
}
return response;
}
} services.AddScoped(typeof(IPipelineBehavior<,>), typeof(CachingBehavior <,>));