如何使用内存缓存(IMemoryCache)

1 缓存基础知识

缓存是实际工做中很是经常使用的一种提升性能的方法。api

缓存能够减小生成内容所需的工做,从而显著提升应用程序的性能和可伸缩性。 缓存最适用于不常常更改的数据。 经过缓存,能够比从原始数据源返回的数据的副本速度快得多。缓存

2 使用内存缓存(IMemoryCache)

首先,咱们简单的建立一个控制器,实现一个简单方法,返回当前时间。咱们能够看到每次访问这个接口,均可以看到当前时间。函数

[Route("api/[controller]")]
[ApiController]
public class CacheController : ControllerBase
{
    [HttpGet]
    public string Get()
    {
        return DateTime.Now.ToString();
    }
}

而后,将Microsoft.Extensions.Caching.Memory的NuGet软件包安装到您的应用程序中。性能

Microsoft.Extensions.Caching.Memory

接着,使用依赖关系注入从应用中引用的服务,在Startup类的ConfigureServices()方法中配置:测试

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}

接着,在构造函数中请求IMemoryCache实例this

private IMemoryCache cache;
public CacheController(IMemoryCache cache)
{
    this.cache = cache ?? throw new ArgumentNullException(nameof(cache));
}

最后,在Get方法中使用缓存code

[HttpGet]
public string Get()
{
    //读取缓存
    var now = cache.Get<string>("cacheNow");
    if (now == null) //若是没有该缓存
    {
        now = DateTime.Now.ToString();
        cache.Set("cacheNow", now);
        return now;
    }
    else
    {
        return now;
    }
}

通过测试能够看到,缓存后,咱们取到日期就从内存中得到,而不须要每次都去计算,说明缓存起做用了。接口

相关文章
相关标签/搜索