.net 缓存

123 阅读1分钟

一、客户端缓存

在方法上添加[ResponseCache(Duration = 20)],表明缓存多少秒

image.png

此后每次都会捎带 max-age=20 这个请求头

image.png

二、服务器缓存

app.MapContrillers()之前加上app.UseResponseCaching().

确保app.UseCors()写到app.UseResponseCaching()之前,

即顺序为 :

app.UseCors()

app.UseResponseCaching()

app.MapContrillers()

image.png

三、内存缓存

3.1 添加服务

builder.Services.AddMemoryCache();

image.png

3.2 自定义数据库查询逻辑

namespace WebApplication1
{
    public class MyDbContext
    {
        public static Task<User?> GetByIdAsync(long id)
        {
            return Task.FromResult(GetById(id));
        }

        public static User GetById(long id)
        {
            if (id == 1)
            {
               return new User("张三",16);
            }
            if (id ==2)            {
                return new User("lisi", 22);
            }
            else
            {
                return null;
            }

        }
    }
}

3.3 接口调用

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class TestController : ControllerBase
    {
        private readonly IMemoryCache memoryCache;

        public TestController(IMemoryCache memoryCache)
        {
            this.memoryCache = memoryCache;
        }

        [HttpGet]
        public async Task<ActionResult<User>> GetById(long id)
        {
            await Console.Out.WriteLineAsync("开始查询");
            User? user = await memoryCache.GetOrCreateAsync("User" + id, async (e) =>
            {
                await Console.Out.WriteLineAsync("数据库中查询");
                return await MyDbContext.GetByIdAsync(id);
            });
            await Console.Out.WriteLineAsync("查询结束");
            if (user == null)
            {
                return NotFound($"id为{id}的用户不存在");
            }
            else
            {
                return Ok(user);
            }
          
        }

        [ResponseCache(Duration = 20)]
        [HttpGet]
        public DateTime Now()
        {
            return DateTime.Now;
        }

    }
}

3.4 结果查询

多次查询同一id的对象时,第二次以后不再查询数据库

image.png

3.5 注

3.5.1 绝对过期时间

设置缓存有效时间

e.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10);

image.png

3.5.2 滑动过期时间

滑动过期时间:

10秒内没有访问则过期,若有访问,结束后重新开始计时

e.SlidingExpiration = TimeSpan.FromSeconds(10);

image.png

3.5.3 绝对与滑动策略混用

image.png