Net Core使用Redis
Net Core操作redis
·
1.添加依赖包
使用NuGet添加依赖包:Microsoft.Extensions.Caching.StackExchangeRedis
点击安装,我本地已经安装好了,所以只需要更新即可。
2.Redis注册
在Startup文件的ConfigureServices方法中添加对Redis的注册
services.AddStackExchangeRedisCache(redis =>
{
redis.Configuration = CommonBLL.Config["DBString:RedisConn"];//配置文件配置
redis.InstanceName = "Test";//自定义
});
注意:在向Redis中存储键值对时的键为“InstanceName+自己定义的键”,因此可以通过设置不同的InstanceName来为不同的Application在Redis中做数据隔离,这就是InstanceName的作用
3.添加RedisHelper
在程序中添加RedisHelper.cs类,下面给出两种方式
(1)方式一,该方式不包含对byte的操作
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Test.Models
{
public class RedisHelper
{
/// <summary>
/// redis连接字符串
/// </summary>
private static readonly string RedisConnString = CommonBLL.Config["DBString:RedisConn"];
//相当于上面设置的InstanceName
private static readonly string RedisKey = CommonBLL.Config["DBString:RedisKey"];
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private int DbNum { get; }
#region ConnectionMultiplexer实例
/// <summary>
/// 单例获取
/// </summary>
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = ConnectionMultiplexer.Connect(RedisConnString);
}
}
}
return _instance;
}
}
public RedisHelper(int dbnum = 1)
{
DbNum = dbnum;
}
#endregion
#region 扩展方法
private T Do<T>(Func<IDatabase, T> func)
{
var database = Instance.GetDatabase(DbNum);
return func(database);
}
private string ConvertJson<T>(T value)
{
return JsonConvert.SerializeObject(value);
}
private T ConvertObj<T>(RedisValue value)
{
return JsonConvert.DeserializeObject<T>(value);
}
private List<T> ConvertList<T>(RedisValue[] value)
{
List<T> result = new List<T>();
foreach (var item in value)
{
result.Add(ConvertObj<T>(item));
}
return result;
}
private RedisKey[] ConvertRedisKeys(List<string> rediskey)
{
return rediskey.Select(key => (RedisKey)key).ToArray();
}
#endregion
#region String
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public string StringGet(string key)
{
key = RedisKey + key;
return Do(db => db.StringGet(key));
}
public string StringGet(string key, string CustomKey)
{
key = RedisKey + key;
return Do(db => db.StringGet(CustomKey + key));
}
/// <summary>
/// 自定义key前缀
/// </summary>
/// <param name="key"></param>
/// <param name="isAdd"></param>
/// <returns></returns>
public string StringGet(string key, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db => db.StringGet(key));
}
/// <summary>
/// 新增String键值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool StringSet(string key, string value)
{
key = RedisKey + key;
return Do(db => db.StringSet(key, value));
}
/// <summary>
/// String键值自增
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool IncrKey(string key)
{
key = RedisKey + key;
return Do(db => (db.StringIncrement(key) > 0) ? true : false);
}
#endregion
#region List
/// <summary>
/// 获取列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public List<T> ListRange<T>(string key)
{
key = RedisKey + key;
return Do(redis =>
{
var values = redis.ListRange(key);
return ConvertList<T>(values);
});
}
/// <summary>
/// 左侧插入数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListLeftPush<T>(string key, T value)
{
key = RedisKey + key;
Do(db => db.ListLeftPush(key, ConvertJson(value)));
}
/// <summary>
/// 右侧插入数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRightPush<T>(string key, T value)
{
key = RedisKey + key;
Do(db => db.ListRightPush(key, ConvertJson(value)));
}
/// <summary>
/// 对List中指定位置,重新赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="index"></param>
/// <param name="value"></param>
public void ListLSet<T>(string key, int index, T value)
{
key = RedisKey + key;
Do(db =>
{
db.ListSetByIndex(key, index, ConvertJson(value));
return true;
});
}
#endregion
#region Hash
/// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashExists(string key, string dataKey)
{
key = RedisKey + key;
return Do(db => db.HashExists(key, dataKey));
}
/// <summary>
/// 单个值存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool HashSet<T>(string key, string dataKey, T t)
{
key = RedisKey + key;
return Do(db =>
{
string str = t.ToString();
return db.HashSet(key, dataKey, str);
});
}
/// <summary>
/// 单个值存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="isAdd">是否需要加上前缀:1是 0否</param>
/// <param name="t"></param>
/// <returns></returns>
public bool HashSet<T>(string key, string dataKey, T t, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
string str = t.ToString();
return db.HashSet(key, dataKey, str);
});
}
/// <summary>
/// 单个值自增
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="num"></param>
/// <returns></returns>
public bool HashSetIncr(string key, string dataKey, int num)
{
key = RedisKey + key;
return Do(db =>
{
return db.HashIncrement(key, dataKey, num) > 0;
});
}
/// <summary>
/// 单个值自增
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="num"></param>
/// <returns></returns>
public bool HashSetIncr(string key, string dataKey, int num, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
return db.HashIncrement(key, dataKey, num) > 0;
});
}
/// <summary>
/// 多值(field)存储Hash
/// </summary>
/// <param name="key"></param>
/// <param name="hashstr"></param>
public void HashMSet(string key, HashEntry[] hashstr)
{
key = RedisKey + key;
var db = Instance.GetDatabase(DbNum);
db.HashSet(key, hashstr);
}
/// <summary>
/// 获取hash所有键值对
/// </summary>
/// <param name="key"></param>
/// <param name="isAdd">是否需要加上前缀:1是 0否</param>
/// <returns></returns>
public HashEntry[] HashGetAll(string key, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
return db.HashGetAll(key);
});
}
public RedisValue[] HashGetAll(string key, RedisValue[] datafiled)
{
key = RedisKey + key;
return Do(db =>
{
return db.HashGet(key, datafiled);
});
}
/// <summary>
/// 获取hash单个键值对
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public string HashGet(string key, string dataKey)
{
key = RedisKey + key;
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return db.HashGet(key, dataKey).ToString();
});
}
/// <summary>
/// 获取hash单个键值对
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="isAdd">是否加前缀:1是 0否</param>
/// <returns></returns>
public string HashGet(string key, string dataKey, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return db.HashGet(key, dataKey).ToString();
});
}
/// <summary>
/// 对Hash进行排序
/// </summary>
/// <param name="key"></param>
/// <param name="getfiled"></param>
/// <returns></returns>
public RedisValue[] HashSort(string key, string sortfiled, int sortOrder, RedisValue[] getfiled)
{
key = RedisKey + key;
return Do(db =>
{
return db.Sort(key, 0, -1, sortOrder == 1 ? Order.Ascending : Order.Descending, SortType.Numeric, sortfiled, getfiled);
});
}
#endregion
#region key
/// <summary>
/// 设置key值过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool KeyExpire(string key, TimeSpan expiry)
{
key = RedisKey + key;
return Do(db => db.KeyExpire(key, expiry));
}
/// <summary>
/// key是否存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool KeyExists(string key)
{
key = RedisKey + key;
return Do(db => db.KeyExists(key));
}
/// <summary>
/// 模糊查询key名称,获取key集合(!!!注意,使用值时,不要再加前缀)
/// </summary>
/// <param name="pattern">关键字</param>
/// <returns></returns>
public List<string> GetLikeKey(string pattern)
{
pattern = RedisKey + pattern + "*";
return Do(db =>
{
var result = db.ScriptEvaluate(LuaScript.Prepare(" local res= redis.call('KEYS',@keypattern) return res"), new { @keypattern = pattern });
List<string> list = new List<string>((string[])result);
return list;
});
}
/// <summary>
/// 删除单个key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool KeyDelete(string key)
{
key = RedisKey + key;
return Do(db => db.KeyDelete(key));
}
/// <summary>
/// 根据关键字,模糊查询key集合,并删除
/// </summary>
/// <param name="pattern">关键字</param>
/// <returns></returns>
public long KeysDelete(string pattern)
{
return Do(db =>
{
var _server = _instance.GetServer(_instance.GetEndPoints()[DbNum]);
var keys = _server.Keys(db.Database, pattern + "*");
return db.KeyDelete(keys.ToArray());
});
}
/// <summary>
/// 删除key集合
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long KeysDelete(List<string> key)
{
RedisKey[] value = ConvertRedisKeys(key);
return Do(db => db.KeyDelete(value));
}
#endregion
}
}
(2)方式二,该方式不包含对List和Hash的操作,增加对byte的操作
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.StackExchangeRedis;
using System.Threading;
using System.Threading.Tasks;
namespace Test.Models
{
public class RedisHelperSelf
{
public RedisCache redisCache;
public RedisCacheOptions redisCacheOptions;
public RedisHelperSelf()
{
redisCacheOptions=new RedisCacheOptions();
redisCacheOptions.Configuration= CommonBLL.Config["DBString:RedisConn"];
redisCacheOptions.InstanceName = "Test";
redisCache=new RedisCache(redisCacheOptions);
}
//注意:在向Redis中存储键值对时的键为“InstanceName+自己定义的键”,因此可以通过设置不同的InstanceName来为不同的Application在Redis中做数据隔离,这就是InstanceName的作用
#region byte[]
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key"></param>
/// <returns>byte[]</returns>
public byte[] Get(string key)
{
return redisCache.Get(key);
}
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key"></param>
/// <param name="cancellationToken">根据cancellationToken属性,控制结束线程</param>
/// <returns>Task<byte[]></returns>
public Task<byte[]> GetAsync(string key, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.GetAsync(key, cancellationToken);
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Set(string key, byte[] value)
{
redisCache.Set(key, value);
}
/// <summary>
/// 设置缓存以及过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options">设置Redis缓存的过期策略,
/// 可以用其设置缓存的绝对过期时间(AbsoluteExpiration或AbsoluteExpirationRelativeToNow),
/// 例如: new DistributedCacheEntryOptions { AbsoluteExpiration=new System.DateTimeOffset()}
/// new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow=new System.TimeSpan(0, 500000, 0)}
/// 也可以设置缓存的滑动过期时间(SlidingExpiration)
/// 例如:new DistributedCacheEntryOptions { SlidingExpiration=new System.TimeSpan (0,500000,0) }
/// </param>
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
redisCache.Set(key, value, options);
}
/// <summary>
/// 设置缓存以及过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options">同上</param>
/// <returns></returns>
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
{
return redisCache.SetAsync(key, value, options);
}
/// <summary>
/// 设置缓存以及过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options">同上</param>
/// <param name="cancellationToken">根据cancellationToken属性,控制结束线程</param>
/// <returns></returns>
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options,CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.SetAsync(key, value, options,cancellationToken);
}
#endregion
#region String
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key"></param>
/// <returns>string</returns>
public string GetString(string key)
{
return redisCache.GetString(key);
}
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key"></param>
/// <returns>Task<string></returns>
public Task<string> GetStringAsync(string key)
{
return redisCache.GetStringAsync(key);
}
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key"></param>
/// <param name="cancellationToken">根据cancellationToken属性,控制结束线程</param>
/// <returns>Task<string></returns>
public Task<string> GetStringAsync(string key, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.GetStringAsync(key, cancellationToken);
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void SetString(string key,string value)
{
redisCache.SetString(key, value);
}
/// <summary>
/// 设置缓存以及过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options">设置Redis缓存的过期策略,
/// 可以用其设置缓存的绝对过期时间(AbsoluteExpiration或AbsoluteExpirationRelativeToNow),
/// 例如: new DistributedCacheEntryOptions { AbsoluteExpiration=new System.DateTimeOffset()}
/// new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow=new System.TimeSpan(0, 500000, 0)}
/// 也可以设置缓存的滑动过期时间(SlidingExpiration)
/// 例如:new DistributedCacheEntryOptions { SlidingExpiration=new System.TimeSpan (0,500000,0) }
/// </param>
public void SetString(string key, string value, DistributedCacheEntryOptions options)
{
redisCache.SetString(key, value, options);
}
/// <summary>
/// 设置缓存以及过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options"></param>
/// <returns></returns>
public Task SetStringAsync(string key,string value, DistributedCacheEntryOptions options)
{
return redisCache.SetStringAsync(key, value, options);
}
/// <summary>
/// 设置缓存以及过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options"></param>
/// <param name="cancellationToken">根据cancellationToken属性,控制结束线程</param>
/// <returns></returns>
public Task SetStringsync(string key, string value, DistributedCacheEntryOptions options, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.SetStringAsync(key, value, options, cancellationToken);
}
#endregion
#region Refresh
/// <summary>
/// 从Redis中刷新键值
/// </summary>
/// <param name="key">缓存键</param>
public void Refresh(string key)
{
redisCache.Refresh(key);
}
/// <summary>
/// Redis中刷新键值
/// </summary>
/// <param name="key"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task RefreshAsync(string key)
{
return redisCache.RefreshAsync(key);
}
/// <summary>
/// Redis中刷新键值
/// </summary>
/// <param name="key"></param>
/// <param name="cancellationToken">根据cancellationToken属性,控制结束线程</param>
/// <returns></returns>
public Task RefreshAsync(string key, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.RefreshAsync(key, cancellationToken);
}
#endregion
#region Remove
/// <summary>
/// 从Redis中删除键值
/// </summary>
/// <param name="key"></param>
public void Remove(string key)
{
redisCache.Remove(key);
}
/// <summary>
/// 从Redis中删除键值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task RemoveAsync(string key)
{
return redisCache.RemoveAsync(key);
}
/// <summary>
/// 从Redis中删除键值
/// </summary>
/// <param name="key"></param>
/// <param name="cancellationToken">根据cancellationToken属性,控制结束线程</param>
/// <returns></returns>
public Task RemoveAsync(string key,CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.RemoveAsync(key,cancellationToken);
}
#endregion
}
}
更多推荐
已为社区贡献6条内容
所有评论(0)