123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513 |
- using Newtonsoft.Json;
- using ServiceStack.Redis;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Linq;
- using System.Text;
- namespace CP.Common.redis
- {
- public class RedisHelper : IDisposable
- {
- private static RedisClient redisCli = null;
- /// <summary>
- /// 建立连接
- /// </summary>
- /// <param name="redisConfig">redis配置节点</param>
- public static void CreateClient(string redisConfig, bool isAuto = false)
- {
- var json = string.Empty;
- if (!isAuto)
- json = ConfigurationManager.AppSettings["ReidsConfig"]?.ToString().Trim() ?? "";
- else
- json = ConfigurationManager.AppSettings[redisConfig]?.ToString().Trim() ?? "";
- if (string.IsNullOrEmpty(json))
- throw new Exception("初始化redis失败:未找到配置节点");
- RedisConfig config = null;
- try
- {
- config = JsonConvert.DeserializeObject<RedisConfig>(json);
- }
- catch (Exception ex)
- {
- throw new Exception("初始化redis失败:配置节点json数据格式错误。" + ex.Message);
- }
- if (redisCli == null)
- {
- try
- {
- redisCli = new RedisClient(config.host, config.port, config.password, config.db);
- }
- catch (Exception ex)
- {
- throw new Exception("初始化redis失败:" + string.Format("{0}:{1} {2} {3}", config.host, config.port, config.password, config.db) + "\n" + ex.Message);
- }
- }
- }
- public static RedisClient CreateClient2(string redisConfig, bool isAuto = false)
- {
- var json = string.Empty;
- if (!isAuto)
- json = ConfigurationManager.AppSettings["ReidsConfig"]?.ToString().Trim() ?? "";
- else
- json = ConfigurationManager.AppSettings[redisConfig]?.ToString().Trim() ?? "";
- if (string.IsNullOrEmpty(json))
- throw new Exception("初始化redis失败:未找到配置节点");
- RedisConfig config = null;
- try
- {
- config = JsonConvert.DeserializeObject<RedisConfig>(json);
- }
- catch (Exception ex)
- {
- throw new Exception("初始化redis失败:配置节点json数据格式错误。" + ex.Message);
- }
- if (redisCli == null)
- {
- try
- {
- redisCli = new RedisClient(config.host, config.port);
- }
- catch (Exception ex)
- {
- throw new Exception("初始化redis失败:" + string.Format("{0}:{1} {2} {3}", config.host, config.port, config.password, config.db) + "\n" + ex.Message);
- }
- }
- return redisCli;
- }
- /// <summary>
- /// 创建连接池
- /// </summary>
- /// <param name="readWriteHosts"></param>
- /// <param name="readOnlyHosts"></param>
- /// <returns></returns>
- private static PooledRedisClientManager CreatePool(string[] readWriteHosts, string[] readOnlyHosts, int db)
- {
- //支持读写分离,均衡负载
- return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
- {
- DefaultDb = db,
- MaxWritePoolSize = 50,//“写”链接池链接数
- MaxReadPoolSize = 50,//“读”链接池链接数
- AutoStart = true,
- });
- }
- /// <summary>
- /// 使用连接池获取链接
- /// </summary>
- public static void CreateClientByPool(string[] readWriteHosts, string[] readOnlyHosts, int db)
- {
- redisCli = (RedisClient)CreatePool(readWriteHosts, readOnlyHosts, db).GetClient();
- }
- #region string
- /// <summary>
- /// 获取key,返回string格式
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static string GetValueString(string key)
- {
- string value = redisCli.GetValue(key);
- return value;
- }
- public static bool AddValue<T>(string key, T value)
- {
- return redisCli.Add<T>(key, value);
- }
- /// <summary>
- /// 获取key,返回byte[]格式
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static byte[] GetValueByte(string key)
- {
- byte[] value = redisCli.Get(key);
- return value;
- }
- /// <summary>
- /// 删除key
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static bool DeleteKey(string key)
- {
- if (Exists(key))
- return redisCli.Remove(key);
- return false;
- }
- public static bool Exists(string key)
- {
- return redisCli.Exists(key) > 0 ? true : false;
- }
- #endregion
- #region Hash
- public static bool SetEntryInHash(string hashId, string key, string value)
- {
- return redisCli.SetEntryInHash(hashId, key, value);
- }
- public static bool RemoveEntryFromHash(string hashId, string key)
- {
- return redisCli.RemoveEntryFromHash(hashId, key);
- }
- /// <summary>
- /// 获得某个hash型key下的所有字段
- /// </summary>
- /// <param name="hashId"></param>
- /// <returns></returns>
- public static List<string> GetHashFields(string hashId)
- {
- List<string> hashFields = redisCli.GetHashKeys(hashId);
- return hashFields;
- }
- /// <summary>
- /// 获得某个hash型key下的所有值
- /// </summary>
- /// <param name="hashId"></param>
- /// <returns></returns>
- public static List<string> GetHashValues(string hashId)
- {
- List<string> hashValues = redisCli.GetHashValues(hashId);
- return hashValues;
- }
- /// <summary>
- /// 获得hash型key某个字段的值
- /// </summary>
- /// <param name="key"></param>
- /// <param name="field"></param>
- /// <returns></returns>
- public static string GetHashField(string key, string field)
- {
- string value = redisCli.GetValueFromHash(key, field);
- return value;
- }
- /// <summary>
- /// 设置hash型key某个字段的值
- /// </summary>
- /// <param name="key"></param>
- /// <param name="field"></param>
- /// <param name="value"></param>
- public static void SetHashField(string key, string field, string value)
- {
- //return redisCli.SetEntryInHash(key, field, value);
- redisCli.SetEntryInHash(key, field, value);
- }
- /// <summary>
- /// 使某个字段增加
- /// </summary>
- /// <param name="key"></param>
- /// <param name="field"></param>
- /// <param name="incre"></param>
- public static void SetHashIncr(string key, string field, long incre)
- {
- redisCli.IncrementValueInHash(key, field, incre);
- }
- #endregion
- #region List
- /// <summary>
- /// 向list类型数据添加成员,向列表底部(右侧)添加
- /// </summary>
- /// <param name="list"></param>
- /// <param name="item"></param>
- public static void AddItemToListRight(string list, string item)
- {
- redisCli.AddItemToList(list, item);
- }
- /// <summary>
- /// 获取list元素个数
- /// </summary>
- /// <param name="list"></param>
- /// <returns></returns>
- public static long GetListCount(string list)
- {
- return redisCli.GetListCount(list);
- }
- /// <summary>
- /// 获取list所有元素
- /// </summary>
- /// <param name="list"></param>
- /// <returns></returns>
- public static List<string> GetAllItemsFromList(string list)
- {
- return redisCli.GetAllItemsFromList(list);
- }
- /// <summary>
- /// 获取list中某个元素的值
- /// </summary>
- /// <param name="list"></param>
- /// <returns></returns>
- public static void SetItemInList(string list, int index, string value)
- {
- redisCli.SetItemInList(list, index, value);
- }
- /// <summary>
- /// 删除list中某个元素
- /// </summary>
- /// <param name="list"></param>
- /// <param name="value"></param>
- public static void RemoveItemFromList(string list, int index)
- {
- var value = redisCli.GetItemFromList(list, index);
- if (value != null)
- redisCli.RemoveItemFromList(list, value);
- }
- /// <summary>
- /// 向list类型数据添加成员,向列表顶部(左侧)添加
- /// </summary>
- /// <param name="list"></param>
- /// <param name="item"></param>
- public static void AddItemToListLeft(string list, string item)
- {
- redisCli.LPush(list, Encoding.Default.GetBytes(item));
- }
- /// <summary>
- /// 从list类型数据读取所有成员
- /// </summary>
- /// <param name="list"></param>
- /// <returns></returns>
- public static List<string> GetListAllItems(string list)
- {
- List<string> listMembers = redisCli.GetAllItemsFromList(list);
- return listMembers;
- }
- /// <summary>
- /// 从list类型数据指定索引处获取数据,支持正索引和负索引
- /// </summary>
- /// <param name="list"></param>
- /// <param name="index"></param>
- /// <returns></returns>
- public static string GetItemFromList(string list, int index)
- {
- string item = redisCli.GetItemFromList(list, index);
- return item;
- }
- /// <summary>
- /// 向列表底部(右侧)批量添加数据
- /// </summary>
- /// <param name="list"></param>
- /// <param name="values"></param>
- public static void GetRangeToList(string list, List<string> values)
- {
- redisCli.AddRangeToList(list, values);
- }
- #endregion
- #region Set
- /// <summary>
- /// 向集合中添加数据
- /// </summary>
- /// <param name="setId"></param>
- /// <param name="item"></param>
- public static void AddItemToSet(string setId, string item)
- {
- redisCli.AddItemToSet(setId, item);
- }
- /// <summary>
- /// 从集合中移除数据
- /// </summary>
- /// <param name="setId"></param>
- /// <param name="item"></param>
- public static void RemoveItemFromSet(string setId, string item)
- {
- redisCli.RemoveItemFromSet(setId, item);
- }
- /// <summary>
- /// 获得集合中所有数据
- /// </summary>
- /// <param name="set"></param>
- /// <returns></returns>
- public static HashSet<string> GetAllItemsFromSet(string set)
- {
- HashSet<string> items = redisCli.GetAllItemsFromSet(set);
- return items;
- }
- /// <summary>
- /// 获取fromSet集合和其他集合不同的数据
- /// </summary>
- /// <param name="fromSet"></param>
- /// <param name="toSet"></param>
- /// <returns></returns>
- public static HashSet<string> GetSetDiff(string fromSet, params string[] toSet)
- {
- HashSet<string> diff = redisCli.GetDifferencesFromSet(fromSet, toSet);
- return diff;
- }
- /// <summary>
- /// 获得所有集合的并集
- /// </summary>
- /// <param name="set"></param>
- /// <returns></returns>
- public static HashSet<string> GetSetUnion(params string[] set)
- {
- HashSet<string> union = redisCli.GetUnionFromSets(set);
- return union;
- }
- /// <summary>
- /// 获得所有集合的交集
- /// </summary>
- /// <param name="set"></param>
- /// <returns></returns>
- public static HashSet<string> GetSetInter(params string[] set)
- {
- HashSet<string> inter = redisCli.GetIntersectFromSets(set);
- return inter;
- }
- #endregion
- #region SortedSet
- /// <summary>
- /// 向有序集合中添加元素
- /// </summary>
- /// <param name="set"></param>
- /// <param name="value"></param>
- /// <param name="score"></param>
- public static bool AddItemToSortedSet(string set, string value, long score)
- {
- return redisCli.AddItemToSortedSet(set, value, score);
- }
- public static bool AddItemToSortedSet(string set, string value, double score)
- {
- return redisCli.AddItemToSortedSet(set, value, score);
- }
- /// <summary>
- /// 获得某个值在有序集合中的排名,按分数的降序排列
- /// </summary>
- /// <param name="set"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static long GetItemIndexInSortedSetDesc(string set, string value)
- {
- long index = redisCli.GetItemIndexInSortedSetDesc(set, value);
- return index;
- }
- /// <summary>
- /// 获得某个值在有序集合中的排名,按分数的升序排列
- /// </summary>
- /// <param name="set"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static long GetItemIndexInSortedSet(string set, string value)
- {
- long index = redisCli.GetItemIndexInSortedSet(set, value);
- return index;
- }
- /// <summary>
- /// 获得有序集合中某个值得分数
- /// </summary>
- /// <param name="set"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static double GetItemScoreInSortedSet(string set, string value)
- {
- double score = redisCli.GetItemScoreInSortedSet(set, value);
- return score;
- }
- /// <summary>
- /// 获得有序集合中,某个排名范围的所有值
- /// </summary>
- /// <param name="set"></param>
- /// <param name="beginRank"></param>
- /// <param name="endRank"></param>
- /// <returns></returns>
- public static List<string> GetRangeFromSortedSet(string set, int beginRank, int endRank)
- {
- List<string> valueList = redisCli.GetRangeFromSortedSet(set, beginRank, endRank);
- return valueList;
- }
- /// <summary>
- /// 获得有序集合中,某个分数范围内的所有值,升序
- /// </summary>
- /// <param name="set"></param>
- /// <param name="beginScore"></param>
- /// <param name="endScore"></param>
- /// <returns></returns>
- public static List<string> GetRangeFromSortedSet(string set, double beginScore, double endScore)
- {
- List<string> valueList = redisCli.GetRangeFromSortedSetByHighestScore(set, beginScore, endScore);
- return valueList;
- }
- /// <summary>
- /// 获得有序集合中,某个分数范围内的所有值,降序
- /// </summary>
- /// <param name="set"></param>
- /// <param name="beginScore"></param>
- /// <param name="endScore"></param>
- /// <returns></returns>
- public static List<string> GetRangeFromSortedSetDesc(string set, double beginScore, double endScore)
- {
- List<string> vlaueList = redisCli.GetRangeFromSortedSetByLowestScore(set, beginScore, endScore);
- return vlaueList;
- }
- public static bool RemoveItemFromScoredSet(string setId, string value)
- {
- bool flag = redisCli.RemoveItemFromSortedSet(setId, value);
- return flag;
- }
- public static bool HasItemFromScoredSet(string setId, string value)
- {
- long index = redisCli.GetItemIndexInSortedSet(setId, value);
- return index < 0 ? false : true;
- }
- #endregion
- public void Dispose()
- {
- redisCli.Dispose();
- }
- }
- }
|