using Newtonsoft.Json; using ServiceStack.Redis; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Data.Entity.Migrations.Model; using System.Linq; using System.Web; namespace MQTTServerSideAPI { public class RedisDBHelper { private static object locker = new object(); public static ConnectionMultiplexer instance = null; // private static string strConn = "127.0.0.1:6379,password=auth"; //public static IDatabase db=null; static RedisDBHelper()//静态构造函数,1、在类实例被初始化的时候执行;2、在类的静态成员被调用的时候执行;3.静态构造函数只会被执行一次;4.静态构造函数不能含有参数 { //string strConn = "127.0.0.1:6379,password=123456";//reids缓存数据库连接字符串 string strConn = "127.0.0.1:7555,password=cw_oy_lsh"; /* */ if (strConn.Length == 0) { throw new Exception("连接字符串未设置!"); } if (instance == null)//单例模式 { lock (locker) { if (instance == null || instance.IsConnected) { instance = ConnectionMultiplexer.Connect(strConn); } } } } /// /// 使用一个静态属性来返回已连接的实例,如下列中所示,这样,一旦ConnectionMultiplexer断开连接,便可以初始化新的连接实例 /// //public static ConnectionMultiplexer instance //{ // get // { // if(Constr.Length==0) // { // throw new Exception("连接字符串未设置!"); // } // if(_instance==null) // { // lock(locker) // { // if(_instance==null||!_instance.IsConnected) // { // _instance = ConnectionMultiplexer.Connect(Constr); // } // } // } // return _instance; // } //} /// /// 将指定键移动到指定数据库 /// /// /// 将数据库num的键移动到movedb数据库 /// /// public static bool KeyMove(string key, int movedb, int num = 0) { return instance.GetDatabase(num).KeyMove(key, movedb); } /// /// 获取指定键的类型 /// /// /// /// public static RedisType KeyType(string key, int num = 0) { return instance.GetDatabase(num).KeyType(key); } /// /// 指定键重命名 /// /// 旧键 /// 新键 /// /// public static bool KeyRename(string oldkey, string newkey, int num = 0) { return instance.GetDatabase(num).KeyRename(oldkey, newkey); } /// /// 指定键是否存在 /// /// 指定键 /// 选择指定数据库 /// public static bool KeyExists(string key, int num = 0) { return instance.GetDatabase(num).KeyExists(key); } /// /// 删除指定键 /// /// /// /// public static bool KeyDelete(string key, int num = 0) { return instance.GetDatabase(num).KeyDelete(key); } /// /// 将键的值转换为byte数组类型 /// /// /// /// public static byte[] KeyDump(string key, int num = 0) { return instance.GetDatabase(num).KeyDump(key); } #region redis字符串操作 /// /// 设置指定键的值 /// /// /// /// 默认为null,设置键过期时间 /// 选择指定的数据库 /// public static bool StringSet(string key, object value, TimeSpan? expire = null, int num = 0) { return instance.GetDatabase(num).StringSet(key, ConvertJson(value), expire); } private static string ConvertJson(T value) { return value is string ? value.ToString() : JsonConvert.SerializeObject(value, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.None }); } /// /// 获取指定键的值 /// /// /// 选择指定的数据库 /// public static string StringGet(string key, int num = 0) { return instance.GetDatabase(num).StringGet(key); } /// /// 反序列化 /// /// 泛型T /// 反序列化 字符串 /// 返回 泛型T 实例 public static T ConvertObj(string value) { if (typeof(T).Name.ToLower().Equals("string")) { return (T)(Object)value; } return JsonConvert.DeserializeObject(value); } /// /// key-value同时为多个键设置值,若给定键已经存在,将用新值覆盖旧值 /// /// /// /// public static bool StringSet(KeyValuePair[] keyvaluepair, int num = 0) { return instance.GetDatabase(num).StringSet(keyvaluepair); } /// /// 为多个键分别设置它们的值,仅当键不存在时 /// /// /// public static void StringSet1(KeyValuePair[] keyvaluepair, int num = 0) { foreach (KeyValuePair key in keyvaluepair) { if (instance.GetDatabase(num).StringGet(key.Key) == RedisValue.Null) { instance.GetDatabase(num).StringSet(key.Key, key.Value); } } } /// /// 获取多个键的值 /// /// /// /// public static RedisValue[] StringGet(RedisKey[] keys, int num = 0) { return instance.GetDatabase(0).StringGet(keys); } /// /// 在指定偏移处开始的键处覆盖字符串的一部分 /// /// /// 偏移量 /// /// /// public static string StringSet(string key, long offset, string overstr, int num = 0) { return instance.GetDatabase(num).StringSetRange(key, offset, overstr); } /// /// 获得键的指定部分的值 /// /// /// /// /// /// public static string StringGet(string key, int start, int end, int num) { return instance.GetDatabase(num).StringGetRange(key, start, end); } /// /// 获取指定键的值字符串长度 /// /// /// /// 返回键值字符串长度 public static long StringLength(string key, int num = 0) { return instance.GetDatabase(num).StringLength(key); } /// /// 指定键的值追加字符串 /// /// /// /// /// 返回追加字符串后键值的长度 public static long StringAppend(string key, string appendstr, int num = 0) { return instance.GetDatabase(num).StringAppend(key, appendstr); } /// /// 为值为整数的指定键增加一个整数,默认加1 /// /// /// /// /// 增加一个整数值后的键的值 public static long StringIncrement(string key, int incr, int num = 0) { return instance.GetDatabase(num).StringIncrement(key, incr); } /// /// 为值为整数的指定键增加一个实数 /// /// /// /// /// 增加一个整数值后的键的值 public static double StringIncrement(string key, double incr, int num = 0) { return instance.GetDatabase(num).StringIncrement(key, incr); } /// /// 数值键减少一个整数 /// /// /// /// /// 减少后的值 public static long StringDecrement(string key, int decre, int num = 0) { return instance.GetDatabase(num).StringDecrement(key, decre); } /// /// 数值键减少一个实数 /// /// /// /// /// 减少后的值 public static double StringDecrement(string key, double decre, int num = 0) { return instance.GetDatabase(num).StringDecrement(key, decre); } /// /// 修改键的值 /// /// /// /// /// 返回旧值 public static string StringGetSet(string key, string newvalue, int num = 0) { return instance.GetDatabase(num).StringGetSet(key, newvalue); } #endregion #region hash type operation /// /// 判断键中的field是否存在 /// /// /// /// /// public static bool HashExists(string key, string hashfield, int num) { return instance.GetDatabase(num).HashExists(key, hashfield); } /// /// 设置散列字段的字符串值 /// /// /// /// /// public static void HashSet(string key, string field, string value, int num = 0) { if (!HashExists(key, field, num))//仅当字段不存在时,才设置散列字段的值 { instance.GetDatabase(num).HashSet(key, field, value); } } /// /// 获取存储在指定键的哈希字段的值 /// /// /// /// /// public static object HashGet(string key, string hashfield, int num = 0) { return instance.GetDatabase(num).HashGet(key, hashfield); } /// /// 为多个哈希字段分别设置它们的值 /// /// /// public static void HashSet(string key, HashEntry[] hashFields, int num = 0) { instance.GetDatabase(num).HashSet(key, hashFields); } /// /// 为多个哈希字段分别设置它们的值 /// /// /// public static void HashPutAll(string key, Dictionary dic, int num = 2) { List list = new List(); for (int i = 0; i < dic.Count; i++) { KeyValuePair param = dic.ElementAt(i); list.Add(new HashEntry(param.Key, param.Value)); instance.GetDatabase(num).HashSet(key, list.ToArray()); } } /// /// 获取指定键的所有哈希字段和值 /// /// /// /// public static Dictionary HashGetAll(string key, int num = 0) { Dictionary dic = new Dictionary(); var collection = instance.GetDatabase(num).HashGetAll(key); foreach (var item in collection) { dic.Add(item.Name, item.Value); } return dic; } /// /// 删除指定键的哈希字段 /// /// /// /// /// public static bool HashDelete(string key, string field, int num) { return instance.GetDatabase(num).HashDelete(key, field); } /// /// 将哈希字段的浮点值按给定数值增加(整数将类型改变即可) /// /// /// /// /// /// public static double HashIncrement(string key, string field, double value, int num = 0) { return instance.GetDatabase(num).HashIncrement(key, field, value); } /// /// 将哈希字段的浮点值按给定数值减少(整数将类型改变即可) /// /// /// /// /// /// public static double HashDecrement(string key, string field, double value, int num = 0) { return instance.GetDatabase(num).HashDecrement(key, field, value); } /// /// 获取哈希中的所有字段fields /// /// /// /// public static string[] HashKeys(string key, int num = 0) { return instance.GetDatabase(num).HashKeys(key).ToStringArray(); } /// /// 获取哈希中的所有值 /// /// /// /// public static string[] HashValues(string key, int num = 0) { return instance.GetDatabase(num).HashValues(key).ToStringArray(); } /// /// 获取散列中的字段数量 /// /// /// /// public static long HashSize(string key, int num = 0) { return instance.GetDatabase(num).HashLength(key); } #endregion #region list operation /// /// 从左向右压栈(从右往左同理) /// /// /// /// /// public static long ListLeftPush(string key, string value, int num = 0) { return instance.GetDatabase(num).ListLeftPush(key, value); } /// /// 多个值压栈(从右往左同理) /// /// /// /// /// public static long ListLeftPush(string key, RedisValue[] values, int num = 0) { return instance.GetDatabase(num).ListLeftPush(key, values); } /// /// 出栈 /// /// /// /// 返回从左到右的第一个元素 public static object ListLeftPop(string key, int num) { return instance.GetDatabase(num).ListLeftPop(key); } /// /// 获取list长度 /// /// /// /// public static long ListSize(string key, int num) { return instance.GetDatabase(num).ListLength(key); } /// /// 范围检索 /// /// /// /// /// /// 返回list public static RedisValue[] ListRange(string key, long start = 0, long stop = -1, int num = 0) { return instance.GetDatabase(num).ListRange(key, start, stop); } /// /// 根据索引获得值 /// /// /// /// /// 返回索引对应的值 public static RedisValue ListGetByIndex(string key, long index, int num = 0) { return instance.GetDatabase(num).ListGetByIndex(key, index); } /// /// 通过索引赋值 /// /// /// /// /// public static void ListSet(string key, int index, string value, int num = 0) { instance.GetDatabase(num).ListSetByIndex(key, index, value); } /// /// 移除key中值为value的i个,返回删除的个数,如果没有这个元素,则返回0 /// /// /// /// /// public static long ListRemove(string key, string value, int num = 0) { return instance.GetDatabase(num).ListRemove(key, value); } /// /// 删除除了[start,end]以外的所有元素 /// /// /// /// /// public static void ListTrim(string key, int start, int end, int num = 0) { instance.GetDatabase(num).ListTrim(key, start, end); } /// /// 将源key的队列的右边的一个值删除,然后塞入目标key的队列的左边,返回这个值 /// /// /// /// /// public static object ListRightPopAndLeftPush(string sourceKey, string destinationKey, int num = 0) { return instance.GetDatabase(num).ListRightPopLeftPush(sourceKey, destinationKey); } /// /// 在key队列中pivot值后插入value值 /// /// /// /// /// /// public static long ListInsertAfter(string key, string pivot, string value, int num = 0) { return instance.GetDatabase(num).ListInsertAfter(key, pivot, value); } /// /// 在key队列中pivot值前插入value值 /// /// /// /// /// /// public static long ListInsertBefore(string key, string pivot, string value, int num = 0) { return instance.GetDatabase(num).ListInsertBefore(key, pivot, value); } #endregion #region set opetation /// /// 集合添加元素 /// /// 缓存的键 /// 值 /// 键 public static void SetAdd(string key, string value, int num = 0) { instance.GetDatabase(num).SetAdd(key, value); } public static void SetAdd(string key, RedisValue[] values, int num) { instance.GetDatabase(num).SetAdd(key, values); } /// /// 集合中是否包含value值 /// /// /// /// /// public static bool SetContains(string key, string value, int num = 0) { return instance.GetDatabase(num).SetContains(key, value); } /// /// 获得集合的长度 /// /// /// /// public static long SetSize(string key, int num = 0) { return instance.GetDatabase(num).SetLength(key); } /// /// 根据键值返回集合所有的value /// /// /// /// public static RedisValue[] GetSetMembers(string key, int num = 0) { return instance.GetDatabase(num).SetMembers(key); } /// /// 将成员从源集合移动到目标集合 /// /// /// /// /// /// public static bool SetMove(string sourceKey, string destinationKey, string value, int num = 0) { return instance.GetDatabase(num).SetMove(sourceKey, destinationKey, value); } /// /// 移除集合中指定键值随机元素 /// /// /// /// public static string SetPop(string key, int num = 0) { return instance.GetDatabase(num).SetPop(key); } /// /// 返回集合中指定键值随机元素 /// /// /// /// public static string SetRandomMember(string key, int num = 0) { return instance.GetDatabase(num).SetRandomMember(key); } /// /// 返回集合中指定键值随机的count个元素形成数组 /// /// /// /// /// public static string[] setRandomMembers(string key, long count, int num = 0) { return instance.GetDatabase(num).SetRandomMembers(key, count).ToStringArray(); } /// /// 移除集合中指定key和value /// /// /// /// public static void SetRemove(string key, string value, int num = 0) { instance.GetDatabase(num).SetRemove(key, value); } /// /// /// /// /// public static void SetScan(String key, int num = 0) { instance.GetDatabase(num).SetScan(key); } /// /// 返回对给定集合进行指定操作产生的集合成员 /// /// /// /// /// /// public static RedisValue[] SetCombine(SetOperation operation, string first, string second, int num = 0) { return instance.GetDatabase(num).SetCombine(operation, first, second); } #endregion } }