博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
RedisHelper帮助类
阅读量:6293 次
发布时间:2019-06-22

本文共 16889 字,大约阅读时间需要 56 分钟。

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
StringSetAsync(string key, string value, int secondTimeout) { return await Do(db => db.StringSetAsync(key, value, TimeSpan.FromSeconds(secondTimeout))); } ///
/// 保存多个key value /// ///
键值对 ///
public static async Task
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
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
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
StringIncrementAsync(string key, long val = 1) { return await Do(db => db.StringIncrementAsync(key, val)); } ///
/// 为数字减少val /// ///
///
可以为负 ///
减少后的值
public static async Task
StringDecrementAsync(string key, long val = 1) { return await Do(db => db.StringDecrementAsync(key, val)); } ///
/// 为数字增长val /// ///
///
可以为负 ///
增长后的值
public static async Task
StringIncrementAsync(string key, double val = 1) { return await Do(db => db.StringIncrementAsync(key, val)); } ///
/// 为数字减少val /// ///
///
可以为负 ///
减少后的值
public static async Task
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
HashExistsAsync(string key, string dataKey) { return await Do(db => db.HashExistsAsync(key, dataKey)); } ///
/// 存储数据到hash表 /// ///
///
///
///
///
public static async Task
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
HashDelAsync(string key, string dataKey) { return await Do(db => db.HashDeleteAsync(key, dataKey)); } ///
/// 移除hash中的多个值 /// ///
///
///
public static async Task
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
HashIncrementAsync(string key, string dataKey, double val = 1) { return await Do(db => db.HashIncrementAsync(key, dataKey, val)); } ///
/// 为数字减少val /// ///
///
///
可以为负 ///
减少后的值
public static async Task
HashDecrementAsync(string key, string dataKey, long val = 1) { return await Do(db => db.HashDecrementAsync(key, dataKey, val)); } ///
/// 为数字增长val /// ///
///
///
可以为负 ///
增长后的值
public static async Task
HashIncrementAsync(string key, string dataKey, long val = 1) { return await Do(db => db.HashIncrementAsync(key, dataKey, val)); } ///
/// 为数字减少val /// ///
///
///
可以为负 ///
减少后的值
public static async Task
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
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
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
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
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
SortedSetAddAsync
(string key, T value, double score) { return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson
(value), score)); } ///
/// 删除 /// ///
///
public static async Task
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
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
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
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
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
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(); } }}

 

转载地址:http://xzcta.baihongyu.com/

你可能感兴趣的文章
Morris ajax
查看>>
【Docker学习笔记(四)】通过Nginx镜像快速搭建静态网站
查看>>
ORA-12514: TNS: 监听程序当前无法识别连接描述符中请求的服务
查看>>
<转>云主机配置OpenStack使用spice的方法
查看>>
java jvm GC 各个区内存参数设置
查看>>
[使用帮助] PHPCMS V9内容模块PC标签调用说明
查看>>
关于FreeBSD的CVSROOT的配置
查看>>
基于RBAC权限管理
查看>>
数学公式的英语读法
查看>>
留德十年
查看>>
迷人的卡耐基说话术
查看>>
PHP导出table为xls出现乱码解决方法
查看>>
PHP问题 —— 丢失SESSION
查看>>
Java中Object类的equals()和hashCode()方法深入解析
查看>>
数据库
查看>>
Vue------第二天(计算属性、侦听器、绑定Class、绑定Style)
查看>>
dojo.mixin(混合进)、dojo.extend、dojo.declare
查看>>
Python 数据类型
查看>>
iOS--环信集成并修改头像和昵称(需要自己的服务器)
查看>>
PHP版微信权限验证配置,音频文件下载,FFmpeg转码,上传OSS和删除转存服务器本地文件...
查看>>