码迷,mamicode.com
首页 > 其他好文 > 详细

Redis 操作帮助类

时间:2019-08-21 11:17:13      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:else   index   lse   error:   mem   each   void   exce   operation   

首先从Nuget中添加StackExchange.Redis包

1、Redis连接对象管理帮助类

using Mvc.Base;
using Mvc.Base.Log;
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace RedisApi
{
    /// <summary>
    /// Redis连接对象管理帮助类
    /// </summary>
    public static class RedisConnectionHelp
    {
 
        /// <summary>
        /// 获取Redis连接字符串
        /// </summary>
        private static readonly string RedisConnectionString = BaseMethod.GetAppValue("RedisConnectionString");
 
 
        /// <summary>
        /// 线程锁
        /// </summary>
        private static readonly object Locker = new object();
 
 
        /// <summary>
        /// Redis连接对象
        /// </summary>
        private static ConnectionMultiplexer _instance;
 
 
        /// <summary>
        /// 获取单例连接对象
        /// </summary>
        public static ConnectionMultiplexer Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (Locker)
                    {
                        if (_instance == null || !_instance.IsConnected)
                        {
                            _instance = GetManager();
                        }
                    }
                }
                return _instance;
            }
        }
 
 
        /// <summary>
        /// 连接Redis
        /// </summary>
        /// <returns></returns>
        private static ConnectionMultiplexer GetManager()
        {
            ConnectionMultiplexer connect = null;
            try
            {
                connect = ConnectionMultiplexer.Connect(RedisConnectionString);
            }
            catch
            {
                return null;
            }
 
            //注册事件
            connect.ConnectionFailed += MuxerConnectionFailed;
            connect.ConnectionRestored += MuxerConnectionRestored;
            connect.ErrorMessage += MuxerErrorMessage;
            connect.ConfigurationChanged += MuxerConfigurationChanged;
            connect.HashSlotMoved += MuxerHashSlotMoved;
            connect.InternalError += MuxerInternalError;
 
            return connect;
        }
 
 
        #region 注册事件
 
 
        /// <summary>
        /// 配置更改时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
        {
            LogHelper.WriteLog("Configuration changed: " + e.EndPoint);
        }
 
        /// <summary>
        /// 发生错误时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
        {
            LogHelper.WriteLog("ErrorMessage: " + e.Message);
        }
 
        /// <summary>
        /// 重新建立连接之前的错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
        {
            LogHelper.WriteLog("ConnectionRestored: " + e.EndPoint);
        }
 
        /// <summary>
        /// 连接失败 , 如果重新连接成功你将不会收到这个通知
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
        {
            LogHelper.WriteLog("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
        }
 
        /// <summary>
        /// 更改集群
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
        {
            LogHelper.WriteLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
        }
 
        /// <summary>
        /// redis类库错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
        {
            LogHelper.WriteLog("InternalError:Message" + e.Exception.Message);
        }
 
 
        #endregion 事件
 
 
    }
}

 

数据库连接是从config配置文件中读取的,配置示例

<!--Redis连接地址-->
<add key="RedisConnectionString" value="localhost:6000,allowadmin=true,password=8611561"/>

 

 

2、Redis操作帮助类

using Mvc.Base.Data;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace RedisApi
{
    /// <summary>
    /// Redis操作帮助类
    /// </summary>
    public class RedisHelper
    {
 
        /// <summary>
        /// 数据库编号
        /// </summary>
        private int DbNum;
 
 
        /// <summary>
        /// 连接对象
        /// </summary>
        private readonly ConnectionMultiplexer RedisConn;
 
 
        /// <summary>
        /// 用构造函数创建一个Redis实例
        /// </summary>
        /// <param name="_DbNum">数据库编号</param>
        public RedisHelper(int _DbNum)
        {
            DbNum = _DbNum;
            RedisConn = RedisConnectionHelp.Instance;
        }
 
 
 
        #region ----------------------String 操作----------------------
 
 
        /// <summary>
        /// 添加或更新一个String值
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public bool StringSet(string Key, string Value)
        {
            try
            {
                return Do(db => db.StringSet(Key, Value));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 批量添加或更新String值
        /// </summary>
        /// <param name="Values">String集合</param>
        /// <returns></returns>
        public bool StringSet(Dictionary<string, string> Values)
        {
            try
            {
                List<KeyValuePair<RedisKey, RedisValue>> _KeyValuePair = new List<KeyValuePair<RedisKey, RedisValue>>();
                foreach (var item in Values.Keys)
                {
                    _KeyValuePair.Add(new KeyValuePair<RedisKey, RedisValue>(item, Values[item]));
                }
                return Do(db => db.StringSet(_KeyValuePair.ToArray()));
            }
            catch
            {
                return false;
            }
 
        }
 
 
 
 
        /// <summary>
        /// 获取String值
        /// </summary>
        /// <param name="Key">Redis Key</param>
        /// <returns></returns>
        public string StringGet(string Key)
        {
            try
            {
                return Do(db => db.StringGet(Key));
            }
            catch
            {
                return null;
            }
        }
 
 
 
 
        /// <summary>
        /// 批量获取String值
        /// </summary>
        /// <param name="ListKey">Value集合</param>
        /// <returns></returns>
        public List<string> StringGet(List<string> ListKey)
        {
            try
            {
                return RedisValueToList(Do(db => db.StringGet(ListToRedisKey(ListKey))));
            }
            catch
            {
                return null;
            }
        }
 
 
 
 
        /// <summary>
        /// 将指定键上的值做加法运算
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value">要增长的值(可以为负)</param>
        /// <returns>增长后的值</returns>
        public double StringIncrement(string Key, double Value)
        {
            try
            {
                return Do(db => db.StringIncrement(Key, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 将指定键上的值做减法运算
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value">要减少的值(可以为负)</param>
        /// <returns>减少后的值</returns>
        public double StringDecrement(string Key, double Value)
        {
            try
            {
                return Do(db => db.StringDecrement(Key, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 根据键获取截取之后的值
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">起始位置</param>
        /// <param name="End">结束位置</param>
        /// <returns>截取之后的值</returns>
        public string StringGetRange(string Key, long Start, long End)
        {
            try
            {
                return Do(db => db.StringGetRange(Key, Start, End));
            }
            catch
            {
                return null;
            }
        }
 
 
 
 
        /// <summary>
        /// 使键上的值追加一个字符串,若不存在该键则创建并设置为空字符串后追加 
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value">追加值</param>
        /// <returns>追加操作后字符串的长度</returns>
        public long StringAppend(string Key, string Value)
        {
            try
            {
                return Do(db => db.StringAppend(Key, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
        #endregion
 
 
        #region  ---------------------- Hash 操作 ----------------------
 
 
        /// <summary>
        /// 根据键存储一对键值到Hash表
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKey">Hash键</param>
        /// <param name="HashValue">Hash值</param>
        /// <returns></returns>
        public bool HashSet(string Key, string HashKey, string HashValue)
        {
            try
            {
                return Do(db =>
                {
                    return db.HashSet(Key, HashKey, HashValue);
                });
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 根据键存储多对键值到Hash表
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashTable">Hash表</param>
        /// <returns></returns>
        public void HashSet(string Key, Dictionary<string, string> HashData)
        {
            try
            {
                List<HashEntry> HashTable = new List<HashEntry>();
                foreach (string item in HashData.Keys)
                {
                    HashTable.Add(new HashEntry(item, HashData[item]));
                }
                var db = RedisConn.GetDatabase(DbNum);
                db.HashSet(Key, HashTable.ToArray());
            }
            catch
            {
 
            }
        }
 
 
 
 
        /// <summary>
        /// 获取该键上的Hash表的元素总数
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public long HashLength(string Key)
        {
            try
            {
                return Do(db => db.HashLength(Key));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 将指定键上的Hash表的值做加法运算
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKey">HashKey</param>
        /// <param name="Value">增加值,可以为负</param>
        /// <returns>增长后的值</returns>
        public double HashIncrement(string Key, string HashKey, double Value)
        {
            try
            {
                return Do(db => db.HashIncrement(Key, HashKey, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 将指定键上的Hash表的值做减法运算
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKey">HashKey</param>
        /// <param name="Value">减少值,可以为负</param>
        /// <returns>减少后的值</returns>
        public double HashDecrement(string Key, string HashKey, double Value)
        {
            try
            {
                return Do(db => db.HashDecrement(Key, HashKey, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取该键上的Hash表,键不存在返回0
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public Dictionary<string, string> HashGetAll(string Key)
        {
            try
            {
                HashEntry[] HashTable = Do(db => db.HashGetAll(Key));
                Dictionary<string, string> Result = new Dictionary<string, string>();
                for (int i = 0; i < HashTable.Length; i++)
                {
                    Result.Add(HashTable[i].Name, HashTable[i].Value.ToString());
                }
                return Result;
            }
            catch
            {
                return new Dictionary<string, string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 获取该键上的Hash表上的Key对应的值
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKey">Hash键</param>
        /// <returns></returns>
        public string HashGet(string Key, string HashKey)
        {
            try
            {
                return Do(db => db.HashGet(Key, HashKey));
            }
            catch
            {
                return null;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取该键上的Hash表上的批量Key对应的批量值
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKeys">Hash键集合</param>
        /// <returns></returns>
        public List<string> HashGet(string Key, string[] HashKeys)
        {
            try
            {
                RedisValue[] _RedisValue = new RedisValue[HashKeys.Length];
                for (int i = 0; i < HashKeys.Length; i++)
                {
                    _RedisValue[i] = HashKeys[i];
                }
                return Do(db =>
                {
                    RedisValue[] Value = db.HashGet(Key, _RedisValue);
                    List<string> Result = new List<string>();
                    for (int i = 0; i < Value.Length; i++)
                    {
                        Result.Add(Value[i].ToString());
                    }
                    return Result;
                });
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 返回该键上的Hash表上的Key是否已经添加
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKey">Hash键</param>
        /// <returns></returns>
        public bool HashExists(string Key, string HashKey)
        {
            try
            {
                return Do(db => db.HashExists(Key, HashKey));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 移除该键上的Hash表上的键值
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKey">Hash键</param>
        /// <returns></returns>
        public bool HashDelete(string Key, string HashKey)
        {
            try
            {
                return Do(db => db.HashDelete(Key, HashKey));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        ///  批量移除该键上的Hash表上的键值
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="HashKeys">Hash键集合</param>
        /// <returns></returns>
        public long HashDelete(string Key, string[] HashKeys)
        {
            try
            {
                RedisValue[] _RedisValue = new RedisValue[HashKeys.Length];
                for (int i = 0; i < HashKeys.Length; i++)
                {
                    _RedisValue[i] = HashKeys[i];
                }
                return Do(db => db.HashDelete(Key, _RedisValue));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取该键上的Hash表上的所有Key
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public List<string> HashKeys(string Key)
        {
            try
            {
                return Do(db => RedisValueToList(db.HashKeys(Key)));
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
        #endregion
 
 
        #region ------------------------List  操作 ----------------------
 
 
        /// <summary>
        /// 入队,加入到List尾部
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        public long ListRightPush(string Key, string Value)
        {
            try
            {
                return Do(db => db.ListRightPush(Key, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 出队,获取尾部元素并移除
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string ListRightPop(string Key)
        {
            try
            {
                return Do(db => db.ListRightPop(Key));
            }
            catch
            {
                return null;
            }
        }
 
 
 
 
        /// <summary>
        /// 入栈,加入到List头部
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        public long ListLeftPush(string Key, string Value)
        {
            try
            {
                return Do(db => db.ListLeftPush(Key, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 出栈,获取头部元素并移除
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string ListLeftPop(string Key)
        {
            try
            {
                return Do(db => db.ListLeftPop(Key));
            }
            catch
            {
                return null;
            }
        }
 
 
 
 
        /// <summary>
        /// 移除指定List的某个元素
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value">元素值</param>
        public long ListRemove(string Key, string Value)
        {
            try
            {
                return Do(db => db.ListRemove(Key, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取指定Key的List
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">起始位置</param>
        /// <param name="End">结束位置</param>
        /// <returns></returns>
        public List<string> ListGet(string Key, long Start = 1, long End = 0)
        {
            try
            {
                Start--;
                End--;
                return RedisValueToList(Do(db => db.ListRange(Key, Start, End)));
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 返回存储在键列表中的索引索引中的元素。
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Index">元素索引,负指数可用于指定起始于尾部的元素。-1表示最后一个元素,-2表示倒数第二个</param>
        /// <returns></returns>
        public string ListGetByIndex(string Key, long Index)
        {
            try
            {
                return Do(db => db.ListGetByIndex(Key, Index));
            }
            catch
            {
                return null;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取集合中的数量
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public long ListLength(string Key)
        {
            try
            {
                return Do(redis => redis.ListLength(Key));
            }
            catch
            {
                return -1;
            }
        }
 
 
        #endregion
 
 
        #region ------------------------Set  操作-----------------------
 
 
        /// <summary>
        /// 增加一条数据到Set集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public bool SetAdd(string Key, string Value)
        {
            try
            {
                return Do(db => db.SetAdd(Key, Value));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 增加多条数据到Set集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value">值集合</param>
        /// <returns></returns>
        public long SetAdd(string Key, List<string> Value)
        {
            try
            {
                return Do(db => db.SetAdd(Key, ListToRedisValue(Value)));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 将多个Set集合进行运算操作,返回运算后的集合
        /// </summary>
        /// <param name="Operation">运算标识,0:并集去重,1:交集,2:差集</param>
        /// <param name="Keys">键集合</param>
        /// <returns></returns>
        public List<string> SetCombine(int Operation, List<string> Keys)
        {
            try
            {
                SetOperation operation = SetOperation.Union;
                switch (Operation)
                {
                    case 1:
                        operation = SetOperation.Intersect;
                        break;
                    case 2:
                        operation = SetOperation.Difference;
                        break;
                }
 
                return RedisValueToList(Do(db => db.SetCombine(operation, ListToRedisKey(Keys))));
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 将2个Set集合进行运算操作,返回运算后的集合
        /// </summary>
        /// <param name="Operation">运算标识,0:并集,1:交集,2:差集</param>
        /// <param name="First">集合1</param>
        /// <param name="Second">集合2</param>
        /// <returns></returns>
        public List<string> SetCombine(int Operation, string First, string Second)
        {
            try
            {
                SetOperation operation = SetOperation.Union;
                switch (Operation)
                {
                    case 1:
                        operation = SetOperation.Intersect;
                        break;
                    case 2:
                        operation = SetOperation.Difference;
                        break;
                }
 
                return RedisValueToList(Do(db => db.SetCombine(operation, First, Second)));
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 返回该Set集合的元素数量
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public long SetLength(string Key)
        {
            try
            {
                return Do(db => db.SetLength(Key));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取该Set集合所有元素
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public List<string> SetMembers(string Key)
        {
            try
            {
                return RedisValueToList(Do(db => db.SetMembers(Key)));
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 删除Set集合中的某个元素
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public bool SetRemove(string Key, string Value)
        {
            try
            {
                return Do(db => db.SetRemove(Key, Value));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 批量删除Set集合中的元素
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value">值集合</param>
        /// <returns></returns>
        public long SetRemove(string Key, List<string> Value)
        {
            try
            {
                return Do(db => db.SetRemove(Key, ListToRedisValue(Value)));
            }
            catch
            {
                return -1;
            }
        }
 
 
        #endregion
 
 
        #region --------------------SortedSet  操作--------------------
 
 
        /// <summary>
        /// 增加一条数据到SortedSet集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <param name="OrderValue">分数,作为排序依据</param>
        /// <returns></returns>
        public bool SortedSetAdd(string Key, string Value, double OrderValue)
        {
            try
            {
                return Do(db => db.SortedSetAdd(Key, Value, OrderValue));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 增加多条数据到SortedSet集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="SortedSetData">元素集合{ 值,排序值 }</param>
        /// <returns></returns>
        public long SortedSetAdd(string Key, Dictionary<string, double> SortedSetData)
        {
            try
            {
                List<SortedSetEntry> SortedSetTable = new List<SortedSetEntry>();
                foreach (var item in SortedSetData.Keys)
                {
                    SortedSetTable.Add(new SortedSetEntry(item, SortedSetData[item]));
                }
                return Do(db => db.SortedSetAdd(Key, SortedSetTable.ToArray()));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 返回该SortedSet集合的元素数量
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public long SortedSetLength(string Key)
        {
            try
            {
                return Do(db => db.SortedSetLength(Key));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 将指定SortedSet的值的分数做加法运算
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="SortedSetValue"></param>
        /// <param name="Value">增加值,可以为负</param>
        /// <returns>增长后的值</returns>
        public double SortedSetIncrement(string Key, string SortedSetValue, double Value)
        {
            try
            {
                return Do(db => db.SortedSetIncrement(Key, SortedSetValue, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 将指定SortedSet的值的分数做减法运算
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="SortedSetValue"></param>
        /// <param name="Value">减少值,可以为负</param>
        /// <returns>减少后的值</returns>
        public double SortedSetDecrement(string Key, string SortedSetValue, double Value)
        {
            try
            {
                return Do(db => db.SortedSetDecrement(Key, SortedSetValue, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 返回排序后的元素的值的集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">起始排名</param>
        /// <param name="End">结束排名</param>
        /// <param name="OrderType">正序或倒序 0:低-高  1:高-低 </param>
        /// <returns></returns>
        public List<string> SortedSetRangeByRank(string Key, long Start = 1, long End = 0, int OrderType = 0)
        {
            try
            {
                Order _Order = default(Order);
                SortedSetParm(ref Start, ref End, OrderType, ref _Order);
                return RedisValueToList(Do(db => db.SortedSetRangeByRank(Key, Start, End, _Order)));
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 返回排序后的元素集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">起始排名</param>
        /// <param name="End">结束排名</param>
        /// <param name="OrderType">正序或倒序 0:低-高  1:高-低</param>
        /// <returns></returns>
        public Dictionary<string, double> SortedSetRangeByRankWithScores(string Key, long Start = 1, long End = 0, int OrderType = 0)
        {
            try
            {
                Order _Order = default(Order);
                SortedSetParm(ref Start, ref End, OrderType, ref _Order);
 
                SortedSetEntry[] _SortedSetEntry = Do(db => db.SortedSetRangeByRankWithScores(Key, Start, End, _Order));
                Dictionary<string, double> Result = new Dictionary<string, double>();
                foreach (var item in _SortedSetEntry)
                {
                    Result.Add(item.Element, item.Score);
                }
                return Result;
            }
            catch
            {
                return new Dictionary<string, double>();
            }
        }
 
 
 
 
        /// <summary>
        /// 返回指定分数区间的元素的值的集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">最低分</param>
        /// <param name="End">最高分</param>
        /// <param name="OrderType">正序或倒序 0:低-高  1:高-低</param>
        /// <returns></returns>
        public List<string> SortedSetRangeByScore(string Key, long Start = 1, long End = 0, int OrderType = 0)
        {
            try
            {
                Order _Order = default(Order);
                SortedSetParm(ref Start, ref End, OrderType, ref _Order);
                return RedisValueToList(Do(db => db.SortedSetRangeByScore(Key, Start, End, Exclude.None, _Order)));
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// 返回指定分数区间的元素集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">最低分</param>
        /// <param name="End">最高分</param>
        /// <param name="OrderType">正序或倒序 0:低-高  1:高-低</param>
        /// <returns></returns>
        public Dictionary<string, double> SortedSetRangeByScoreWithScores(string Key, long Start = 1, long End = 0, int OrderType = 0)
        {
            try
            {
                Order _Order = default(Order);
                SortedSetParm(ref Start, ref End, OrderType, ref _Order);
 
                SortedSetEntry[] _SortedSetEntry = Do(db => db.SortedSetRangeByScoreWithScores(Key, Start, End, Exclude.None, _Order));
                Dictionary<string, double> Result = new Dictionary<string, double>();
                foreach (var item in _SortedSetEntry)
                {
                    Result.Add(item.Element, item.Score);
                }
                return Result;
            }
            catch
            {
                return new Dictionary<string, double>();
            }
        }
 
 
 
 
        /// <summary>
        /// 获取某个元素的排名
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public long? SortedSetRank(string Key, string Value)
        {
            try
            {
                return Do(db => db.SortedSetRank(Key, Value)) + 1;
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取某个元素的分数
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public double? SortedSetScore(string Key, string Value)
        {
            try
            {
                return Do(db => db.SortedSetScore(Key, Value));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 删除SortedSet集合中某个元素
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public bool SortedSetRemove(string Key, string Value)
        {
            try
            {
                return Do(db => db.SortedSetRemove(Key, Value));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 批量删除SortedSet集合中的元素
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value">值集合</param>
        /// <returns></returns>
        public long SortedSetRemove(string Key, List<string> Value)
        {
            try
            {
                return Do(db => db.SortedSetRemove(Key, ListToRedisValue(Value)));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 删除排名区间的元素
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">起始排名</param>
        /// <param name="End">结束排名</param>
        /// <returns></returns>
        public long SortedSetRemoveRangeByRank(string Key, long Start, long End)
        {
            try
            {
                Start--;
                End--;
                return Do(db => db.SortedSetRemoveRangeByRank(Key, Start, End));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 删除分数区间的元素
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Start">最小值</param>
        /// <param name="End">最大值</param>
        /// <returns></returns>
        public long SortedSetRemoveRangeByScore(string Key, double Start, double End)
        {
            try
            {
                return Do(db => db.SortedSetRemoveRangeByScore(Key, Start, End));
            }
            catch
            {
                return -1;
            }
        }
 
 
        #endregion
 
 
        #region ------------------------Key  操作-----------------------
 
 
        /// <summary>
        /// 删除某个键
        /// </summary>
        /// <param name="Key"></param>
        /// <returns>是否删除成功</returns>
        public bool KeyDelete(string Key)
        {
            try
            {
                return Do(db => db.KeyDelete(Key));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 批量删除键
        /// </summary>
        /// <param name="Keys">键集合</param>
        /// <returns>成功删除的个数</returns>
        public long KeyDelete(List<string> Keys)
        {
            try
            {
                return Do(db => db.KeyDelete(ListToRedisKey(Keys)));
            }
            catch
            {
                return -1;
            }
        }
 
 
 
 
        /// <summary>
        /// 判断键是否存在
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public bool KeyExists(string Key)
        {
            try
            {
                return Do(db => db.KeyExists(Key));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 重新命名Key
        /// </summary>
        /// <param name="Key">旧的键</param>
        /// <param name="NewKey">新的键</param>
        /// <returns></returns>
        public bool KeyRename(string Key, string NewKey)
        {
            try
            {
                return Do(db => db.KeyRename(Key, NewKey));
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 设置键的过期时间
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Expiry">时间长度(值+类型): S:秒 M:分钟 H:小时 D:天  例:100S (100秒)</param>
        /// <returns></returns>
        public bool KeyExpire(string Key, string Expiry)
        {
            try
            {
                string Type = Expiry.Substring(Expiry.Length - 1, 1).ToUpper();
                string Value = Expiry.Substring(0, Expiry.Length - 1);
                TimeSpan? Ts = default(TimeSpan?);
 
                switch (Type)
                {
                    case "S":
                        Ts = TimeSpan.FromSeconds(Convert.ToDouble(Value));
                        break;
                    case "M":
                        Ts = TimeSpan.FromMinutes(Convert.ToDouble(Value));
                        break;
                    case "H":
                        Ts = TimeSpan.FromHours(Convert.ToDouble(Value));
                        break;
                    case "D":
                        Ts = TimeSpan.FromDays(Convert.ToDouble(Value));
                        break;
                }
 
                return Do(db => db.KeyExpire(Key, Ts));
            }
            catch
            {
                return false;
            }
        }
 
 
        #endregion
 
 
        #region ------------------------辅助方法------------------------
 
 
        /// <summary>
        /// 设置排序参数
        /// </summary>
        /// <param name="Start">起始位置</param>
        /// <param name="End">结束位置</param>
        /// <param name="OrderType">排序标识</param>
        /// <param name="_Order">排序类型</param>
        private void SortedSetParm(ref  long Start, ref long End, int OrderType, ref Order _Order)
        {
            Start--;
            End--;
            _Order = OrderType == 0 ? Order.Ascending : Order.Descending;
        }
 
 
 
 
        /// <summary>
        /// List转RedisValue
        /// </summary>
        /// <param name="List">List集合</param>
        /// <returns></returns>
        private RedisValue[] ListToRedisValue(List<string> List)
        {
            List<RedisValue> _RedisValue = new List<RedisValue>();
            try
            {
                for (int i = 0; i < List.Count; i++)
                {
                    _RedisValue.Add(List[i]);
                }
                return _RedisValue.ToArray();
            }
            catch
            {
                return new List<RedisValue>().ToArray();
            }
        }
 
 
 
 
        /// <summary>
        /// RedisValue转List
        /// </summary>
        /// <param name="_RedisValue">RedisValue数组</param>
        /// <returns></returns>
        private List<string> RedisValueToList(RedisValue[] _RedisValue)
        {
            List<string> List = new List<string>();
            try
            {
                for (int i = 0; i < _RedisValue.Length; i++)
                {
                    List.Add(_RedisValue[i]);
                }
                return List;
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
 
        /// <summary>
        /// List转RedisKey
        /// </summary>
        /// <param name="List">List集合</param>
        /// <returns></returns>
        private RedisKey[] ListToRedisKey(List<string> List)
        {
            List<RedisKey> RedisKey = new List<RedisKey>();
            try
            {
                for (int i = 0; i < List.Count; i++)
                {
                    RedisKey.Add(List[i]);
                }
                return RedisKey.ToArray();
            }
            catch
            {
                return new List<RedisKey>().ToArray();
            }
        }
 
 
 
 
        /// <summary>
        /// RedisKey转List
        /// </summary>
        /// <param name="_RedisValue">RedisKey数组</param>
        /// <returns></returns>
        private List<string> RedisKeyToList(RedisKey[] _RedisKey)
        {
            List<string> List = new List<string>();
            try
            {
                for (int i = 0; i < _RedisKey.Length; i++)
                {
                    List.Add(_RedisKey[i]);
                }
                return List;
            }
            catch
            {
                return new List<string>();
            }
        }
 
 
 
        /// <summary>
        /// 执行Redis操作
        /// </summary>
        private T Do<T>(Func<IDatabase, T> func)
        {
            var database = RedisConn.GetDatabase(DbNum);
            return func(database);
        }
 
 
        #endregion 辅助方法
 
 
        #region 其他操作
 
 
        /// <summary>
        /// 获取当前Redis连接状态
        /// </summary>
        /// <returns></returns>
        public bool GetConnectSate()
        {
            bool RedisIsConnected = false;
 
            try
            {
                if (RedisCmd.Api != null)
                {
                    RedisIsConnected = RedisCmd.Api.RedisConn.IsConnected ? true : false;
                    return RedisIsConnected;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
 
 
 
 
        /// <summary>
        /// 获取数据库对象
        /// </summary>
        /// <returns></returns>
        public IDatabase GetDatabase()
        {
            return RedisConn.GetDatabase(DbNum);
        }
 
 
        public ITransaction CreateTransaction()
        {
            return GetDatabase().CreateTransaction();
        }
 
 
        public IServer GetServer(string hostAndPort)
        {
            return RedisConn.GetServer(hostAndPort);
        }
 
 
 
        #endregion 其他
 
 
        #region 发布订阅
 
        /// <summary>
        /// Redis发布订阅  订阅
        /// </summary>
        /// <param name="subChannel"></param>
        /// <param name="handler"></param>
        //public void Subscribe(string subChannel, Action<RedisChannel, RedisValue> handler = null)
        //{
        //    ISubscriber sub = RedisConn.GetSubscriber();
        //    sub.Subscribe(subChannel, (channel, message) =>
        //    {
        //        if (handler == null)
        //        {
        //            Console.WriteLine(subChannel + " 订阅收到消息:" + message);
        //        }
        //        else
        //        {
        //            handler(channel, message);
        //        }
        //    });
        //}
 
        /// <summary>
        /// Redis发布订阅  发布
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="channel"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        //public long Publish<T>(string channel, T msg)
        //{
        //    ISubscriber sub = RedisConn.GetSubscriber();
        //    return sub.Publish(channel, (msg));
        //}
 
        /// <summary>
        /// Redis发布订阅  取消订阅
        /// </summary>
        /// <param name="channel"></param>
        //public void Unsubscribe(string channel)
        //{
        //    ISubscriber sub = RedisConn.GetSubscriber();
        //    sub.Unsubscribe(channel);
        //}
 
        /// <summary>
        /// Redis发布订阅  取消全部订阅
        /// </summary>
        //public void UnsubscribeAll()
        //{
        //    ISubscriber sub = RedisConn.GetSubscriber();
        //    sub.UnsubscribeAll();
        //}
 
        #endregion 发布订阅
 
 
    }
}
 

 

 

3、存放Redis操作对象的公共类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace RedisApi
{
 
    /// <summary>
    /// 存放Redis操作对象的公共类
    /// </summary>
    public static class RedisCmd
    {
        /// <summary>
        /// Redis操作对象
        /// </summary>
        public static RedisHelper Api = null;
    }

 }

 

 

4、使用示例

新建一个Web项目,在Global.asax.cs文件中的Application_Start()方法中,添加如下代码

if (RedisCmd.Api == null) {
    RedisHelper RedisApi = new RedisHelper(0);
    RedisCmd.Api = RedisApi;
}

 

 

从Redis中查询数据示例

 if (RedisCmd.Api.KeyExists("Home_Notify"))
 {
      ViewBag.Notify = RedisCmd.Api.HashGet("Home_Notify", "Title");
      ViewBag.ID = RedisCmd.Api.HashGet("Home_Notify", "AutoID");
 }

 

 

向Redis中新增数据示例

  RedisCmd.Api.HashSet("Home_Notify", "Title", NotifyText[0].Title);
  RedisCmd.Api.HashSet("Home_Notify", "AutoID", NotifyText[0].AutoID.ToString());
  RedisCmd.Api.KeyExpire("Home_Notify", "2h");
 

 

Redis 操作帮助类

标签:else   index   lse   error:   mem   each   void   exce   operation   

原文地址:https://www.cnblogs.com/youmingkuang/p/11387402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!