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);
}