如何在业务层实现响应缓存
前言
上次,我們介紹了應(yīng)該在業(yè)務(wù)層實(shí)現(xiàn)管道模式
響應(yīng)緩存是ASP.NET Core中很重要的功能,它可以存儲(chǔ)響應(yīng),并提供來(lái)自緩存的響應(yīng),以便提高程序性能。
響應(yīng)緩存通常是通過(guò)Middleware實(shí)現(xiàn)的:
public?static?class?ResponseCachingExtensions {///?<summary>///?Adds?the?<see?cref="ResponseCachingMiddleware"/>?for?caching?HTTP?responses.///?</summary>///?<param?name="app">The?<see?cref="IApplicationBuilder"/>.</param>public?static?IApplicationBuilder?UseResponseCaching(this?IApplicationBuilder?app){if?(app?==?null){throw?new?ArgumentNullException(nameof(app));}return?app.UseMiddleware<ResponseCachingMiddleware>();} }現(xiàn)在,我們改成由業(yè)務(wù)層實(shí)現(xiàn)響應(yīng)緩存。
實(shí)現(xiàn)
1.引用Nuget包
新建WebAPI項(xiàng)目,引用需要的Nuget包:
Install-Package?MediatR Install-Package?MediatR.Extensions.Microsoft.DependencyInjection Install-Package?Newtonsoft.Json2.新增接口
新增ICacheableQuery接口,表示需要緩存:
public?interface?ICacheableQuery {TimeSpan??SlidingExpiration?{?get;?} }SlidingExpiration:緩存過(guò)期時(shí)間
3.新增緩存管道
利用MediatR的IPipelineBehavior功能,實(shí)現(xiàn)緩存管道:
public?class?CachingBehavior<TRequest,?TResponse>?:?IPipelineBehavior<TRequest,?TResponse>?where?TRequest?:?ICacheableQuery {private?readonly?IDistributedCache?_cache;public?CachingBehavior(IDistributedCache?cache){_cache?=?cache;}public?async?Task<TResponse>?Handle(TRequest?request,?CancellationToken?cancellationToken,?RequestHandlerDelegate<TResponse>?next){TResponse?response;if?(request.SlidingExpiration?==?null){return?await?next();}var key =GetCacheKey(request);var?cachedResponse?=?await?_cache.GetAsync(key,?cancellationToken);if?(cachedResponse?!=?null){response?=?JsonConvert.DeserializeObject<TResponse>(Encoding.UTF8.GetString(cachedResponse));}else{response?=?await?next();var?options?=?new?DistributedCacheEntryOptions?{?SlidingExpiration?=?request.SlidingExpiration?};var?serializedData?=?Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));await?_cache.SetAsync(key,?serializedData,?options,?cancellationToken);return?response;}return?response;} }以TRequest作為緩存Key,如果緩存存在,則反序列化得到緩存的響應(yīng),否則執(zhí)行請(qǐng)求,緩存響應(yīng)。
4.使用緩存管道
修改WeatherForecastController,使用Mediator,設(shè)置緩存時(shí)間為5秒:
public?class?WeatherForecastController?:?ControllerBase {private?readonly?IMediator?_mediator;public?WeatherForecastController(IMediator?mediator){this._mediator?=?mediator;}[HttpGet]public?async?Task<IEnumerable<WeatherForecast>>?Get(){return?await?this._mediator.Send(new?GetWeatherForecastQuery());??????????????} }public?class?GetWeatherForecastQuery?:?IRequest<IEnumerable<WeatherForecast>>,?ICacheableQuery {public?TimeSpan??SlidingExpiration?{?get;?set;?}?=?TimeSpan.FromSeconds(5); }internal?class?GetWeatherForecastQueryHandler?:?IRequestHandler<GetWeatherForecastQuery,?IEnumerable<WeatherForecast>> {public?async?Task<IEnumerable<WeatherForecast>>?Handle(GetWeatherForecastQuery?request,?CancellationToken?cancellationToken){await?Task.Delay(1000);var?rng?=?new?Random();return?Enumerable.Range(1,?1).Select(index?=>?new?WeatherForecast{?TemperatureC?=?rng.Next(-20,?55),Summary?=?Summaries[rng.Next(Summaries.Length)]}).ToArray();} }為了體現(xiàn)效果明顯,代碼里故意加了等待時(shí)間。
運(yùn)行程序,可以看到,第一次請(qǐng)求花了1000多ms,而后的請(qǐng)求都很快,說(shuō)明使用了緩存:
結(jié)論
在本文中,我們學(xué)會(huì)了使用MediatR實(shí)現(xiàn)響應(yīng)緩存。
如果你覺(jué)得這篇文章對(duì)你有所啟發(fā),請(qǐng)關(guān)注我的個(gè)人公眾號(hào)”My IO“
總結(jié)
以上是生活随笔為你收集整理的如何在业务层实现响应缓存的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: AgileConfig 1.5 发布 -
- 下一篇: Abp VNext 集成sharding