首先从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 -;
}
} /// <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 -;
}
} /// <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 -;
}
} #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 -;
}
} /// <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 -;
}
} /// <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 -;
}
} /// <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 = ; 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 = ; 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 = ; 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 = ; i < HashKeys.Length; i++)
{
_RedisValue[i] = HashKeys[i];
}
return Do(db => db.HashDelete(Key, _RedisValue));
}
catch
{
return -;
}
} /// <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 -;
}
} /// <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 -;
}
} /// <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 -;
}
} /// <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 = , long End = )
{
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 -;
}
} #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 -;
}
} /// <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 :
operation = SetOperation.Intersect;
break;
case :
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 :
operation = SetOperation.Intersect;
break;
case :
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 -;
}
} /// <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 -;
}
} #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 -;
}
} /// <summary>
/// 返回该SortedSet集合的元素数量
/// </summary>
/// <param name="Key">键</param>
/// <returns></returns>
public long SortedSetLength(string Key)
{
try
{
return Do(db => db.SortedSetLength(Key));
}
catch
{
return -;
}
} /// <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 -;
}
} /// <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 -;
}
} /// <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 = , long End = , int OrderType = )
{
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 = , long End = , int OrderType = )
{
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 = , long End = , int OrderType = )
{
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 = , long End = , int OrderType = )
{
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)) + ;
}
catch
{
return -;
}
} /// <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 -;
}
} /// <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 -;
}
} /// <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 -;
}
} /// <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 -;
}
} #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 -;
}
} /// <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 - , ).ToUpper();
string Value = Expiry.Substring(, Expiry.Length - );
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 == ? 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 = ; 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 = ; 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 = ; 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 = ; 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();
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[].Title);
RedisCmd.Api.HashSet("Home_Notify", "AutoID", NotifyText[].AutoID.ToString());
RedisCmd.Api.KeyExpire("Home_Notify", "2h");

Redis 操作帮助类的更多相关文章

  1. redis操作帮助类

    RedisHelper.java import redis.clients.jedis.*; import java.util.*; public class RedisHelper { privat ...

  2. php的redis 操作类,适用于单台或多台、多组redis服务器操作

    redis 操作类,包括单台或多台.多组redis服务器操作,适用于业务复杂.高性能要求的 php web 应用. redis.php: <?php /* redis 操作类,适用于单台或多台. ...

  3. Redis操作Set工具类封装,Java Redis Set命令封装

    Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...

  4. Redis操作List工具类封装,Java Redis List命令封装

    Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...

  5. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  6. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

  7. Java的redis 操作类-优化通用版本

    java操作redis多节点处理方式;http://blog.itpub.net/29254281/viewspace-1188644/首先maven引入依赖包 <dependency> ...

  8. 设计模式之PHP项目应用——单例模式设计Memcache和Redis操作类

    1 单例模式简单介绍 单例模式是一种经常使用的软件设计模式. 在它的核心结构中仅仅包括一个被称为单例类的特殊类. 通过单例模式能够保证系统中一个类仅仅有一个实例并且该实例易于外界訪问.从而方便对实例个 ...

  9. spring 的redis操作类RedisTemplate

    spring 集成的redis操作几乎都在RedisTemplate内了. 已spring boot为例, 再properties属性文件内配置好 redis的参数 spring.redis.host ...

随机推荐

  1. Java开发环境之ActiveMQ

    查看更多Java开发环境配置,请点击<Java开发环境配置大全> 柒章:ActiveMQ安装教程 1)去官网下载ActiveMQ安装包 http://activemq.apache.org ...

  2. PHP控制结构if else,while,do while,for,foreach,break ,continue

    php中控制结构有 控制结构 判断分支 if else, 三元运算符,  switch case, 循环 while do while for foreach 跳出 break continue // ...

  3. BootstrapValidator 表单验证超详细教程

    一. 引入js 和css文件 在有jquery和bootstrap的页面里引入 bootstrapValidator.js bootstrapValidator.css 链接: https://pan ...

  4. nodejs 删除空文件

    var fs = require("fs") var path = require("path") var listRealPath = path.resolv ...

  5. InitContainer

    InitContainer 初始化容器 在Pod中,容器是共享存储资源和网络资源的,所以Init Container容器产生的数据是可以被其他容器作用到的.初始化容器有点类似于postStart 钩子 ...

  6. requests+unittest+ddt+xlrd+pymysql+BeautifulReport数据驱动

    # ddcapitestpython XXX接口自动化测试 # 一.数据驱动的思路 1.采用requests+unittest+ddt+xlrd+pymysql+BeautifulReport 2.r ...

  7. LGOJP2051 [AHOI2009]中国象棋

    比较明显的计数dp.不知道为什么被打了状压的tag... 不难发现无论炮放在哪里其实是等价的,需要知道的只有这一列放了一个炮还是两个炮还是还没放,那么可以设\(f[i,j,k]\)表示第\(i\)行, ...

  8. PHP CGI 进程占用CPU过高导致CPU使用达到100%的另类原因

    由于使用的华为云的CDN加速,结果发现我的阿里云服务器突然卡顿,网页打开极慢.登陆华为云CDN管理后台发现最高带宽占用30M,流量短时间内达到10GB以上,这么大的流量我的服务器肯定扛不住啊.于是还跟 ...

  9. windows 10 下使用Navicat for oracle 数据库还原

    一.前期准备 1.安装windows 10系统 2.安装oracle 11g 数据库 3.安装PLsql(也不需要) 4.安装sqlplus(这个必须有) 5.使用下面这个东西新建数据库(不懂创建的话 ...

  10. HBase学习笔记之HBase的安装和配置

    HBase学习笔记之HBase的安装和配置 我是为了调研和验证hbase的bulkload功能,才安装hbase,学习hbase的.为了快速的验证bulkload功能,我安装了一个节点的hadoop集 ...