C#WebApi 对数据进行缓存加快前请求数据的速度
using ClassLibrary1; using ClassLibrary2; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using WebApplication1.IServices; using WebApplication1.Utility.SwaggerExt; namespace WebApplication1.Controllers { public class HomeController :BaseController { public readonly ILogger<HomeController> logger; public HomeController(IMemoryCache memoryCache, ILogger<HomeController> logger) : base(memoryCache) { this.logger = logger; } /// <summary> /// 测试缓存API /// 创建缓存 CreateEntry /// 删除缓存 Remove /// 获取换粗 TryGetValue /// </summary> /// <param name="i"></param> /// <param name="y"></param> /// <returns></returns> [HttpGet] public async Task<ActionResult<Book?>> GetBookById(long id) { //Book? result = MyDbContext.GetById(id); //// 没有从数据库找到对应的书籍信息 //if(result == null) //{ // return NotFound($"找不到id={id}书籍"); //}else //{ // return result; //} // GetOrCreateAsync 方法如果没有找到 key 值的缓存 就会走回调函数 返回所需要的数据 并在缓存创建相应的缓存 logger.LogDebug($"开始执行缓存API测试ID = ${id}"); Book? b = await memoryCache.GetOrCreateAsync("Book" + id, async (e) => { logger.LogDebug($"缓存 中没有找到需要查找的数据,到数据库查询 ID={id}"); return await MyDbContext.GetByIdAsync(id); }); logger.LogDebug($"GetOrCreateAsync结果{b}"); if (b == null) { return NotFound($"找不到id={id}书籍"); }else { return Ok(b); } } } }
Book 类:
namespace WebApplication1 { public record Book(long id,string name); }