ASP .NET Core MemoryCache缓存
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, TimeSpan.FromMinutes(1));
if (_memoryCache.TryGetValue(cacheKey, out string cacheValue2))
_memoryCache.Set(cacheKey, cacheValue, DateTimeOffset.Now.AddHours(1));
//获取值
_memoryCache.Get(cacheKey).ToString();
_memoryCache.Get<string>(cacheKey);
bool isExist = _memoryCache.TryGetValue(cacheKey, out string cacheValue3);
//获取或创建
var c = _memoryCache.GetOrCreate("cache1", entry =>
{
entry.AbsoluteExpiration = DateTimeOffset.Now.AddHours(1);
//entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
return "1";
});
}
}
帮助类
/// <summary>
/// Cache缓存操作类
/// </summary>
public class CacheHelper
{
protected IMemoryCache cache;
/// <summary>
/// </summary>
/// <param name="cache">IMemoryCache</param>
public CacheHelper(IMemoryCache cache)
{
this.cache = cache;
}
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存键</param>
/// <param name="value">缓存string</param>
/// <param name="timeSpan">设置Redis缓存的过期策略</param>
public void SetString(string key, string value, TimeSpan timeSpan) => cache.Set(key, value, timeSpan);
/// <summary>
/// Redis中获取键值
/// </summary>
/// <param name="key">缓存键</param>
/// <returns>缓存String</returns>
public string? GetString(string key) => cache.Get<string>(key);
/// <summary>
/// 查询键值是否存在
/// </summary>
/// <param name="key">缓存键</param>
/// <returns>true:存在,false:不存在</returns>
public bool Exist(string key) => cache.Get(key) != null;
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">缓存键</param>
public void Remove(string key) => cache.Remove(key);
}