我们需要添加一个Redis包:Microsoft.Extensions.Caching.Redis,这是官方的
1.在appsettings.json添加配置,如下图:
说明:
CacheProvider: ConnectionString --- Redis连接
InstanceName ---Redis实例名称
2.在startup添加redis服务,如下图
3.缓存接口 ICacheService
public interface ICacheService
{
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存key</param>
/// <returns></returns>
string Get(string key);
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
string GetString(string key);
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
void AddString(string key, string value);
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存key</param>
/// <param name="value">缓存值</param>
/// <param name="ExpirationTime">绝对过期时间(分钟)</param>
void Add(string key, string value, int ExpirationTime = 20);
/// <summary>
/// 移除缓存
/// </summary>
/// <param name="key"></param>
void Remove(string key);
/// <summary>
/// 更新缓存
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="ExpirationTime"></param>
void Replace(string key, string value, int ExpirationTime = 20);
4.实现接口 ICacheService
public class RedisCacheService:ICacheService
{
private RedisCache _redisCache = null;
public RedisCacheService(RedisCacheOptions options)
{
_redisCache = new RedisCache(options);
}
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存key</param>
/// <returns></returns>
public string Get(string key)
{
try
{
if (!string.IsNullOrEmpty(key))
{
return Encoding.UTF8.GetString(_redisCache.Get(key));
}
else
{
return string.Empty;
}
}
catch
{
return null;
}
}
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存key</param>
/// <param name="value">缓存值</param>
/// <param name="ExpirationTime">绝对过期时间(分钟)</param>
public void Add(string key,string value,int ExpirationTime=20)
{
if (!string.IsNullOrEmpty(key))
{
_redisCache.Set(key, Encoding.UTF8.GetBytes(value), new DistributedCacheEntryOptions()
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(ExpirationTime)
});
}
}
public void AddString(string key, string value)
{
_redisCache.SetString(key,value);
}
public string GetString(string key)
{
return _redisCache.GetString(key);
}
/// <summary>
/// 移除缓存
/// </summary>
/// <param name="key">缓存key</param>
public void Remove(string key)
{
if (!string.IsNullOrEmpty(key))
{
_redisCache.Remove(key);
}
}
/// <summary>
/// 更新缓存
/// </summary>
/// <param name="key">缓存key</param>
/// <param name="value">缓存值</param>
/// <param name="ExpirationTime"></param>
public void Replace(string key, string value, int ExpirationTime = 20)
{
if (!string.IsNullOrEmpty(key))
{
_redisCache.Remove(key);
_redisCache.Set(key, Encoding.UTF8.GetBytes(value), new DistributedCacheEntryOptions()
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(ExpirationTime)
});
}
}
}