net core IMemoryCache 实现缓存

1.Nuget包 添加Microsoft.Extensions.Caching.Memory 程序包

2.Startup.cs 类 ConfigureServices 方法引用服务

services.AddMemoryCache();

 

 

3. 在构造函数中请求IMemoryCache实例

private IMemoryCache cache;
public UserController(IMemoryCache che)
{
cache = che;
}

4.在方法中引用缓存

[Route("getuser")]
public string GetUser()
{
var now = cache.Get<string>("huancun");

if (now == null)
{
now = DateTime.Now.ToString();
cache.Set("huancun", now);
return now;
}

return now;
}

posted on 2022-09-07 15:02  愤怒的小雀  阅读(58)  评论(0编辑  收藏  举报