using Newtonsoft.Json; using RedLockNet.SERedis; using RedLockNet.SERedis.Configuration; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace 秒杀系统 { public class RedisHelper { private static readonly string RedisHost = "127.0.0.1:6379"; private static readonly string RedisHost1 = "127.0.0.2:6379"; private static readonly string RedisPwd = "sa123456"; private static readonly int RedisDbIndex = 0; private static readonly object LockObject = new object(); private static ConnectionMultiplexer _connection; public static ConnectionMultiplexer Connection { get { if (_connection == null) { lock (LockObject) { if (_connection == null || !_connection.IsConnected) { var config = new ConfigurationOptions { AbortOnConnectFail = false, ConnectRetry = 10, ConnectTimeout = 5000, SyncTimeout = 5000, EndPoints = { { RedisHost } }, AllowAdmin = true, KeepAlive = 180, Password = RedisPwd }; _connection = ConnectionMultiplexer.Connect(config); //注册如下事件 _connection.ConnectionFailed += MuxerConnectionFailed; _connection.ErrorMessage += MuxerErrorMessage; _connection.InternalError += MuxerInternalError; } } } return _connection; } } public static RedLockFactory redLockFactory; public static RedLockFactory RedlockFactory { get { if (redLockFactory != null) return redLockFactory; var multiplexers = new List() { Connection }; var redlockFactory = RedLockFactory.Create(multiplexers); return redlockFactory; } } /// /// 获取redis的DB /// /// private static IDatabase GetDatabase() { if (Connection == null || !Connection.IsConnected) { throw new Exception("redis连接有误"); } return Connection.GetDatabase(RedisDbIndex); } #region 记录redis的连接日志 /// /// 连接失败 , 如果重新连接成功你将不会收到这个通知 /// /// /// private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e) { } /// /// redis类库错误 /// /// /// private static void MuxerInternalError(object sender, InternalErrorEventArgs e) { } /// /// 发生错误时 /// /// /// private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e) { } #endregion 记录redis的连接日志 #region String #region 同步方法 /// /// 保存单个key value /// /// Redis Key /// 保存的值 /// 过期时间 /// public static bool StringSet(string key, string value, int secondTimeout) { return Do(db => db.StringSet(key, value, TimeSpan.FromSeconds(secondTimeout))); } /// /// 保存多个key value /// /// 键值对 /// public static bool StringSet(List > keyValues) { List > newkeyValues = keyValues.Select(p => new KeyValuePair (p.Key, p.Value)).ToList(); return Do(db => db.StringSet(newkeyValues.ToArray())); } /// /// 保存一个对象 /// /// /// /// /// /// public static bool StringSet (string key, T obj, int secondTimeout) { var json = ConvertJson(obj); return Do(db => db.StringSet(key, json, TimeSpan.FromSeconds(secondTimeout))); } /// /// 获取单个key的值 /// /// Redis Key /// public static string StringGet(string key) { return Do(db => db.StringGet(key)); } /// /// 获取一个key的对象 /// /// /// /// public static T StringGet (string key) { return Do(db => ConvertObj (db.StringGet(key))); } /// /// 为数字增长val /// /// /// 可以为负 /// 增长后的值 public static long StringIncrement(string key, long val = 1) { return Do(db => db.StringIncrement(key, val)); } /// /// 为数字减少val /// /// /// 可以为负 /// 减少后的值 public static long StringDecrement(string key, long val = 1) { return Do(db => db.StringDecrement(key, val)); } /// /// 为数字增长val /// /// /// 可以为负 /// 增长后的值 public static double StringIncrement(string key, double val = 1) { return Do(db => db.StringIncrement(key, val)); } /// /// 为数字减少val /// /// /// 可以为负 /// 减少后的值 public static double StringDecrement(string key, double val = 1) { return Do(db => db.StringDecrement(key, val)); } #endregion 同步方法 #region 异步方法 /// /// 保存单个key value /// /// Redis Key /// 保存的值 /// 过期时间 /// public static async Task<bool> StringSetAsync(string key, string value, int secondTimeout) { return await Do(db => db.StringSetAsync(key, value, TimeSpan.FromSeconds(secondTimeout))); } /// /// 保存多个key value /// /// 键值对 /// public static async Task<bool> StringSetAsync(List > keyValues) { List > newkeyValues = keyValues.Select(p => new KeyValuePair (p.Key, p.Value)).ToList(); return await Do(db => db.StringSetAsync(newkeyValues.ToArray())); } /// /// 保存一个对象 /// /// /// /// /// /// public static async Task<bool> StringSetAsync (string key, T obj, int secondTimeout) { string json = ConvertJson(obj); return await Do(db => db.StringSetAsync(key, json, TimeSpan.FromSeconds(secondTimeout))); } /// /// 获取单个key的值 /// /// Redis Key /// public static async Task<string> StringGetAsync(string key) { return await Do(db => db.StringGetAsync(key)); } /// /// 获取一个key的对象 /// /// /// /// public static async Task StringGetAsync (string key) { string result = await Do(db => db.StringGetAsync(key)); return ConvertObj (result); } /// /// 为数字增长val /// /// /// 可以为负 /// 增长后的值 public static async Task<long> StringIncrementAsync(string key, long val = 1) { return await Do(db => db.StringIncrementAsync(key, val)); } /// /// 为数字减少val /// /// /// 可以为负 /// 减少后的值 public static async Task<long> StringDecrementAsync(string key, long val = 1) { return await Do(db => db.StringDecrementAsync(key, val)); } /// /// 为数字增长val /// /// /// 可以为负 /// 增长后的值 public static async Task<double> StringIncrementAsync(string key, double val = 1) { return await Do(db => db.StringIncrementAsync(key, val)); } /// /// 为数字减少val /// /// /// 可以为负 /// 减少后的值 public static async Task<double> StringDecrementAsync(string key, double val = 1) { return await Do(db => db.StringDecrementAsync(key, val)); } #endregion 异步方法 #endregion String #region Hash #region 同步方法 /// /// 判断某个数据是否已经被缓存 /// /// /// /// public static bool HashExists(string key, string dataKey) { return Do(db => db.HashExists(key, dataKey)); } /// /// 存储数据到hash表 /// /// /// /// /// /// public static bool HashSet (string key, string dataKey, T t) { return Do(db => { string json = ConvertJson(t); return db.HashSet(key, dataKey, json); }); } /// /// 移除hash中的某值 /// /// /// /// public static bool HashDel(string key, string dataKey) { return Do(db => db.HashDelete(key, dataKey)); } /// /// 移除hash中的多个值 /// /// /// /// public static long HashDel(string key, List dataKeys) { return Do(db => db.HashDelete(key, dataKeys.ToArray())); } /// /// 从hash表获取数据 /// /// /// /// /// public static T HashGet (string key, string dataKey) { return Do(db => { if (!HashExists(key, dataKey)) return default(T); string value = db.HashGet(key, dataKey); return ConvertObj (value); }); } /// /// 为数字增长val /// /// /// /// 可以为负 /// 增长后的值 public static double HashIncrement(string key, string dataKey, double val = 1) { return Do(db => db.HashIncrement(key, dataKey, val)); } /// /// 为数字减少val /// /// /// /// 可以为负 /// 减少后的值 public static double HashDecrement(string key, string dataKey, double val = 1) { return Do(db => db.HashDecrement(key, dataKey, val)); } /// /// 获取hashkey所有Redis key /// /// /// /// public static List HashKeys (string key) { return Do(db => { RedisValue[] values = db.HashKeys(key); return ConvetList (values); }); } /// /// 获取hashkey所有Redis key /// /// /// public static List HashGetAll (string key) { var values = Do(db => db.HashGetAll(key)); return ConvetList (values); } #endregion 同步方法 #region 异步方法 /// /// 判断某个数据是否已经被缓存 /// /// /// /// public static async Task<bool> HashExistsAsync(string key, string dataKey) { return await Do(db => db.HashExistsAsync(key, dataKey)); } /// /// 存储数据到hash表 /// /// /// /// /// /// public static async Task<bool> HashSetAsync (string key, string dataKey, T t) { return await Do(db => { string json = ConvertJson(t); return db.HashSetAsync(key, dataKey, json); }); } /// /// 移除hash中的某值 /// /// /// /// public static async Task<bool> HashDelAsync(string key, string dataKey) { return await Do(db => db.HashDeleteAsync(key, dataKey)); } /// /// 移除hash中的多个值 /// /// /// /// public static async Task<long> HashDelAsync(string key, List dataKeys) { return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray())); } /// /// 从hash表获取数据 /// /// /// /// /// public static async Task HashGeAsync (string key, string dataKey) { string value = await Do(db => db.HashGetAsync(key, dataKey)); return ConvertObj (value); } /// /// 为数字增长val /// /// /// /// 可以为负 /// 增长后的值 public static async Task<double> HashIncrementAsync(string key, string dataKey, double val = 1) { return await Do(db => db.HashIncrementAsync(key, dataKey, val)); } /// /// 为数字减少val /// /// /// /// 可以为负 /// 减少后的值 public static async Task<long> HashDecrementAsync(string key, string dataKey, long val = 1) { return await Do(db => db.HashDecrementAsync(key, dataKey, val)); } /// /// 为数字增长val /// /// /// /// 可以为负 /// 增长后的值 public static async Task<long> HashIncrementAsync(string key, string dataKey, long val = 1) { return await Do(db => db.HashIncrementAsync(key, dataKey, val)); } /// /// 为数字减少val /// /// /// /// 可以为负 /// 减少后的值 public static async Task<double> HashDecrementAsync(string key, string dataKey, double val = 1) { return await Do(db => db.HashDecrementAsync(key, dataKey, val)); } /// /// 获取hashkey所有Redis key /// /// /// /// public static async Task > HashKeysAsync
(string key) { RedisValue[] values = await Do(db => db.HashKeysAsync(key)); return ConvetList (values); } /// /// 获取hashkey所有Redis key /// /// /// /// public static async Task > HashGetAllAsync
(string key) { var values = await Do(db => db.HashGetAllAsync(key)); return ConvetList (values); } #endregion 异步方法 #endregion Hash #region List #region 同步方法 /// /// 移除指定ListId的内部List的值 /// /// /// public static void ListRemove (string key, T value) { Do(db => db.ListRemove(key, ConvertJson(value))); } /// /// 获取指定key的List /// /// /// public static List ListRange (string key) { return Do(redis => { var values = redis.ListRange(key); return ConvetList (values); }); } /// /// 入队 /// /// /// public static void ListRightPush (string key, T value) { Do(db => db.ListRightPush(key, ConvertJson(value))); } /// /// 出队 /// /// /// /// public static T ListRightPop (string key) { return Do(db => { var value = db.ListRightPop(key); return ConvertObj (value); }); } /// /// 入栈 /// /// /// /// public static void ListLeftPush (string key, T value) { Do(db => db.ListLeftPush(key, ConvertJson(value))); } /// /// 出栈 /// /// /// /// public static T ListLeftPop (string key) { return Do(db => { var value = db.ListLeftPop(key); return ConvertObj (value); }); } /// /// 获取集合中的数量 /// /// /// public static long ListLength(string key) { return Do(redis => redis.ListLength(key)); } #endregion 同步方法 #region 异步方法 /// /// 移除指定ListId的内部List的值 /// /// /// public static async Task<long> ListRemoveAsync (string key, T value) { return await Do(db => db.ListRemoveAsync(key, ConvertJson(value))); } /// /// 获取指定key的List /// /// /// public static async Task > ListRangeAsync
(string key) { var values = await Do(redis => redis.ListRangeAsync(key)); return ConvetList (values); } /// /// 入队 /// /// /// public static async Task<long> ListRightPushAsync (string key, T value) { return await Do(db => db.ListRightPushAsync(key, ConvertJson(value))); } /// /// 出队 /// /// /// /// public static async Task ListRightPopAsync (string key) { var value = await Do(db => db.ListRightPopAsync(key)); return ConvertObj (value); } /// /// 入栈 /// /// /// /// public static async Task<long> ListLeftPushAsync (string key, T value) { return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value))); } /// /// 出栈 /// /// /// /// public static async Task ListLeftPopAsync (string key) { var value = await Do(db => db.ListLeftPopAsync(key)); return ConvertObj (value); } /// /// 获取集合中的数量 /// /// /// public static async Task<long> ListLengthAsync(string key) { return await Do(redis => redis.ListLengthAsync(key)); } #endregion 异步方法 #endregion List #region SortedSet 有序集合 #region 同步方法 /// /// 添加 /// /// /// /// public static bool SortedSetAdd (string key, T value, double score) { return Do(redis => redis.SortedSetAdd(key, ConvertJson (value), score)); } /// /// 删除 /// /// /// public static bool SortedSetRemove (string key, T value) { return Do(redis => redis.SortedSetRemove(key, ConvertJson(value))); } /// /// 获取全部 /// /// /// public static List SortedSetRangeByRank (string key) { return Do(redis => { var values = redis.SortedSetRangeByRank(key); return ConvetList (values); }); } /// /// 获取集合中的数量 /// /// /// public static long SortedSetLength(string key) { return Do(redis => redis.SortedSetLength(key)); } #endregion 同步方法 #region 异步方法 /// /// 添加 /// /// /// /// public static async Task<bool> SortedSetAddAsync (string key, T value, double score) { return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson (value), score)); } /// /// 删除 /// /// /// public static async Task<bool> SortedSetRemoveAsync (string key, T value) { return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value))); } /// /// 获取全部 /// /// /// public static async Task > SortedSetRangeByRankAsync
(string key) { var values = await Do(redis => redis.SortedSetRangeByRankAsync(key)); return ConvetList (values); } /// /// 获取集合中的数量 /// /// /// public static async Task<long> SortedSetLengthAsync(string key) { return await Do(redis => redis.SortedSetLengthAsync(key)); } #endregion 异步方法 #endregion SortedSet 有序集合 #region key /// /// 删除单个key /// /// redis key /// 是否删除成功 public static bool KeyDel(string key) { return Do(db => db.KeyDelete(key)); } /// /// 删除多个key /// /// rediskey /// 成功删除的个数 public static long KeyDel(List<string> keys) { return Do(db => db.KeyDelete(ConvertRedisKeys(keys))); } /// /// 判断key是否存储 /// /// redis key /// public static bool KeyExists(string key) { return Do(db => db.KeyExists(key)); } /// /// 设置Key的时间 /// /// redis key /// /// public static bool KeyExpire(string key, int secondTimeout) { return Do(db => db.KeyExpire(key, TimeSpan.FromSeconds(secondTimeout))); } #endregion key #region 辅助方法 private static T Do (Func func) { try { var database = GetDatabase(); return func(database); } catch (Exception ex) { return default(T); } } private static string ConvertJson (T value) { string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value); return result; } private static T ConvertObj (RedisValue value) { if (value.IsNullOrEmpty) { return default(T); } return JsonConvert.DeserializeObject (value.ToString()); } private static List ConvetList (RedisValue[] values) { List result = new List (); foreach (var item in values) { var model = ConvertObj (item); result.Add(model); } return result; } private static RedisKey[] ConvertRedisKeys(List<string> redisKeys) { return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray(); } private static List ConvetList (HashEntry[] values) { List result = new List (); foreach (var item in values) { if (!item.Value.IsNullOrEmpty) { var model = ConvertObj (item.Value); result.Add(model); } } return result; } #endregion 辅助方法 public static IBatch CreateBatch() { return GetDatabase().CreateBatch(); } public static ITransaction CreateTransaction() { return GetDatabase().CreateTransaction(); } //使用Keys *模糊匹配Key public static List<string> GetMatchKeys(string key) { var result = (string[])GetDatabase().ScriptEvaluate(LuaScript.Prepare("return redis.call('KEYS',@keypattern)"), new { keypattern = key }); return result.ToList(); } //使用SCAN模糊匹配Key public static List<string> ScanMatchKeys(string key) { var result = (string[])GetDatabase().ScriptEvaluate( LuaScript.Prepare("local dbsize=redis.call('dbsize') local res=redis.call('scan',0,'match',KEYS[1],'count',dbsize) return res[2]"), new RedisKey[] { key }); return result.ToList(); } } }