ASP .NET Core MemoryCache缓存

发布时间 2023-04-12 20:57:28作者: 雨水的命运

Redis缓存请看这篇博客

安装Nuget包

Microsoft.Extensions.Caching.Memory

添加缓存服务

services.AddMemoryCache();

使用缓存

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

namespace WebApplication2.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{

    private readonly IMemoryCache _memoryCache;

    public WeatherForecastController(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

    [HttpGet]
    public async Task Get()
    {
        string cacheKey = "cachekey";
        string cacheValue = "1";

        //添加缓存
        _memoryCache.Set(cacheKey, cacheValue, new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.Now.AddHours(1)));

        if (_memoryCache.TryGetValue(cacheKey, out string cacheValue2))
            _memoryCache.Set(cacheKey, cacheValue, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(1)));

        //获取值
        _memoryCache.Get(cacheKey).ToString();
        _memoryCache.Get<string>(cacheKey);
        bool isExist = _memoryCache.TryGetValue(cacheKey, out string cacheValue3);

        //获取或创建
        var c = _memoryCache.GetOrCreate("cache1", entry =&gt;
         {
             entry.AbsoluteExpiration = DateTimeOffset.Now.AddHours(1);
             //entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
             return "1";
         });
    }
}