日常工作中免不了用缓存,总不能在每个代码块加上缓存
我用Qjx.CustomCache 中间件,进行AOP拦截,统一设置API缓存
步骤如下
(1)引入nuget:Qjx.CustomCache
(2)改造Program
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) //改用Autofac来实现依赖注入 .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
(3)改造Startup
public IConfiguration Configuration { get; } //autofac 新增 public ILifetimeScope AutofacContainer { get; private set; } public void ConfigureServices(IServiceCollection services) { //支持redis services.AddRedisCacheSetup(o=> { o.Configuration = "localhost"; }); //支持本地缓存 //services.AddMemoryCacheSetup(); //other code } public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterType<CacheAOP>(); var assembly = this.GetType().GetTypeInfo().Assembly; builder.RegisterAssemblyTypes(assembly).EnableClassInterceptors(); }
(4)改造API 在需要AOP拦截的类上加上
[Intercept(typeof(CacheAOP))]
[Intercept(typeof(CacheAOP))] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase
(5)改造方法
在需要缓存的地方加上如下缓存单位S
[Caching(AbsoluteExpiration = 1000, KeyName = "id-{#id}", Method = CacheMethod.Add)
]
[Route("adddata1")] [HttpGet] [Caching(AbsoluteExpiration = 1000, KeyName = "id-{#id}", Method = CacheMethod.Add) ] public virtual Xuliehua adddata1([FromQuery] Myid myid) { Debug.WriteLine("this is getnme"); Xuliehua hua = new Xuliehua(); hua.obj = DateTime.Now.ToString(); return hua; }