.net 缓存


theme: cyanosis

一、客户端缓存

在方法上添加[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 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值