ASP.NET Core 中的缓存内存

Nuget 包:System.Runtime.Caching

依赖注入:

public class HomeController : Controller
{
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

定义键:

public static class CacheKeys
{
    public static string Entry { get { return "_Entry"; } }
}

赋值与取值:

public IActionResult CacheTryGetValueSet()
{
    DateTime cacheEntry;

    // 尝试从缓存获取,若获取失败则重新赋值
    if (!_cache.TryGetValue(CacheKeys.Entry, out cacheEntry))
    {
        // 新的内容
        cacheEntry = DateTime.Now;

        // 缓存选项
        var cacheEntryOptions = new MemoryCacheEntryOptions()
            // Keep in cache for this time, reset time if accessed.
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(3));

        // 保存到缓存中
        _cache.Set(CacheKeys.Entry, cacheEntry, cacheEntryOptions);
    }

    return View("Cache", cacheEntry);
}

注意:

.SetAbsoluteExpiration() 用于设置绝对过期时间,它表示只要时间一到就过期

.SetSlidingExpiration() 用于设置可调过期时间,它表示当离最后访问超过某个时间段后就过期

xoyozo 3 年前
转载请注明出处
云服务器 精选特惠
可能相关的内容