之前我有一篇文章一片绍了一下Redis,在自己的实践操作中,自己写了一个关于Redis操作的类库
首先从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
{
///
/// Redis连接对象管理帮助类
///
public static class RedisConnectionHelp
{
///
/// 获取Redis连接字符串
///
private static readonly string RedisConnectionString = BaseMethod.GetAppValue("RedisConnectionString");
///
/// 线程锁
///
private static readonly object Locker = new object();
///
/// Redis连接对象
///
private static ConnectionMultiplexer _instance;
///
/// 获取单例连接对象
///
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
}
///
/// 连接Redis
///
///
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 注册事件
///
/// 配置更改时
///
///
///
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
LogHelper.WriteLog("Configuration changed: " + e.EndPoint);
}
///
/// 发生错误时
///
///
///
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
LogHelper.WriteLog("ErrorMessage: " + e.Message);
}
///
/// 重新建立连接之前的错误
///
///
///
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
LogHelper.WriteLog("ConnectionRestored: " + e.EndPoint);
}
///
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
///
///
///
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
LogHelper.WriteLog("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
///
/// 更改集群
///
///
///
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
LogHelper.WriteLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
///
/// redis类库错误
///
///
///
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
LogHelper.WriteLog("InternalError:Message" + e.Exception.Message);
}
#endregion 事件
}
}
数据库连接是从config配置文件中读取的,配置示例
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
{
///
/// Redis操作帮助类
///
public class RedisHelper
{
///
/// 数据库编号
///
private int DbNum;
///
/// 连接对象
///
private readonly ConnectionMultiplexer RedisConn;
///
/// 用构造函数创建一个Redis实例
///
/// 数据库编号
public RedisHelper(int _DbNum)
{
DbNum = _DbNum;
RedisConn = RedisConnectionHelp.Instance;
}
#region ----------------------String 操作----------------------
///
/// 添加或更新一个String值
///
/// 键
/// 值
///
public bool StringSet(string Key, string Value)
{
try
{
return Do(db => db.StringSet(Key, Value));
}
catch
{
return false;
}
}
///
/// 批量添加或更新String值
///
/// String集合
///
public bool StringSet(Dictionary Values)
{
try
{
List> _KeyValuePair = new List>();
foreach (var item in Values.Keys)
{
_KeyValuePair.Add(new KeyValuePair(item, Values[item]));
}
return Do(db => db.StringSet(_KeyValuePair.ToArray()));
}
catch
{
return false;
}
}
///
/// 获取String值
///
/// Redis Key
///
public string StringGet(string Key)
{
try
{
return Do(db => db.StringGet(Key));
}
catch
{
return null;
}
}
///
/// 批量获取String值
///
/// Value集合
///
public List StringGet(List ListKey)
{
try
{
return RedisValueToList(Do(db => db.StringGet(ListToRedisKey(ListKey))));
}
catch
{
return null;
}
}
///
/// 将指定键上的值做加法运算
///
/// 键
/// 要增长的值(可以为负)
/// 增长后的值
public double StringIncrement(string Key, double Value)
{
try
{
return Do(db => db.StringIncrement(Key, Value));
}
catch
{
return -1;
}
}
///
/// 将指定键上的值做减法运算
///
/// 键
/// 要减少的值(可以为负)
/// 减少后的值
public double StringDecrement(string Key, double Value)
{
try
{
return Do(db => db.StringDecrement(Key, Value));
}
catch
{
return -1;
}
}
///
/// 根据键获取截取之后的值
///
/// 键
/// 起始位置
/// 结束位置
/// 截取之后的值
public string StringGetRange(string Key, long Start, long End)
{
try
{
return Do(db => db.StringGetRange(Key, Start, End));
}
catch
{
return null;
}
}
///
/// 使键上的值追加一个字符串,若不存在该键则创建并设置为空字符串后追加
///
/// 键
/// 追加值
/// 追加操作后字符串的长度
public long StringAppend(string Key, string Value)
{
try
{
return Do(db => db.StringAppend(Key, Value));
}
catch
{
return -1;
}
}
#endregion
#region ---------------------- Hash 操作 ----------------------
///
/// 根据键存储一对键值到Hash表
///
/// 键
/// Hash键
/// Hash值
///
public bool HashSet(string Key, string HashKey, string HashValue)
{
try
{
return Do(db =>
{
return db.HashSet(Key, HashKey, HashValue);
});
}
catch
{
return false;
}
}
///
/// 根据键存储多对键值到Hash表
///
/// 键
/// Hash表
///
public void HashSet(string Key, Dictionary HashData)
{
try
{
List HashTable = new List();
foreach (string item in HashData.Keys)
{
HashTable.Add(new HashEntry(item, HashData[item]));
}
var db = RedisConn.GetDatabase(DbNum);
db.HashSet(Key, HashTable.ToArray());
}
catch
{
}
}
///
/// 获取该键上的Hash表的元素总数
///
/// 键
///
public long HashLength(string Key)
{
try
{
return Do(db => db.HashLength(Key));
}
catch
{
return -1;
}
}
///
/// 将指定键上的Hash表的值做加法运算
///
/// 键
/// HashKey
/// 增加值,可以为负
/// 增长后的值
public double HashIncrement(string Key, string HashKey, double Value)
{
try
{
return Do(db => db.HashIncrement(Key, HashKey, Value));
}
catch
{
return -1;
}
}
///
/// 将指定键上的Hash表的值做减法运算
///
/// 键
/// HashKey
/// 减少值,可以为负
/// 减少后的值
public double HashDecrement(string Key, string HashKey, double Value)
{
try
{
return Do(db => db.HashDecrement(Key, HashKey, Value));
}
catch
{
return -1;
}
}
///
/// 获取该键上的Hash表,键不存在返回0
///
/// 键
///
public Dictionary HashGetAll(string Key)
{
try
{
HashEntry[] HashTable = Do(db => db.HashGetAll(Key));
Dictionary Result = new Dictionary();
for (int i = 0; i < HashTable.Length; i++)
{
Result.Add(HashTable[i].Name, HashTable[i].Value.ToString());
}
return Result;
}
catch
{
return new Dictionary();
}
}
///
/// 获取该键上的Hash表上的Key对应的值
///
/// 键
/// Hash键
///
public string HashGet(string Key, string HashKey)
{
try
{
return Do(db => db.HashGet(Key, HashKey));
}
catch
{
return null;
}
}
///
/// 获取该键上的Hash表上的批量Key对应的批量值
///
/// 键
/// Hash键集合
///
public List 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 Result = new List();
for (int i = 0; i < Value.Length; i++)
{
Result.Add(Value[i].ToString());
}
return Result;
});
}
catch
{
return new List();
}
}
///
/// 返回该键上的Hash表上的Key是否已经添加
///
/// 键
/// Hash键
///
public bool HashExists(string Key, string HashKey)
{
try
{
return Do(db => db.HashExists(Key, HashKey));
}
catch
{
return false;
}
}
///
/// 移除该键上的Hash表上的键值
///
/// 键
/// Hash键
///
public bool HashDelete(string Key, string HashKey)
{
try
{
return Do(db => db.HashDelete(Key, HashKey));
}
catch
{
return false;
}
}
///
/// 批量移除该键上的Hash表上的键值
///
/// 键
/// Hash键集合
///
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;
}
}
///
/// 获取该键上的Hash表上的所有Key
///
/// 键
///
public List HashKeys(string Key)
{
try
{
return Do(db => RedisValueToList(db.HashKeys(Key)));
}
catch
{
return new List();
}
}
#endregion
#region ------------------------List 操作 ----------------------
///
/// 入队,加入到List尾部
///
/// 键
/// 值
public long ListRightPush(string Key, string Value)
{
try
{
return Do(db => db.ListRightPush(Key, Value));
}
catch
{
return -1;
}
}
///
/// 出队,获取尾部元素并移除
///
/// 键
///
public string ListRightPop(string Key)
{
try
{
return Do(db => db.ListRightPop(Key));
}
catch
{
return null;
}
}
///
/// 入栈,加入到List头部
///
/// 键
/// 值
public long ListLeftPush(string Key, string Value)
{
try
{
return Do(db => db.ListLeftPush(Key, Value));
}
catch
{
return -1;
}
}
///
/// 出栈,获取头部元素并移除
///
/// 键
///
public string ListLeftPop(string Key)
{
try
{
return Do(db => db.ListLeftPop(Key));
}
catch
{
return null;
}
}
///
/// 移除指定List的某个元素
///
/// 键
/// 元素值
public long ListRemove(string Key, string Value)
{
try
{
return Do(db => db.ListRemove(Key, Value));
}
catch
{
return -1;
}
}
///
/// 获取指定Key的List
///
/// 键
/// 起始位置
/// 结束位置
///
public List 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();
}
}
///
/// 返回存储在键列表中的索引索引中的元素。
///
/// 键
/// 元素索引,负指数可用于指定起始于尾部的元素。-1表示最后一个元素,-2表示倒数第二个
///
public string ListGetByIndex(string Key, long Index)
{
try
{
return Do(db => db.ListGetByIndex(Key, Index));
}
catch
{
return null;
}
}
///
/// 获取集合中的数量
///
/// 键
///
public long ListLength(string Key)
{
try
{
return Do(redis => redis.ListLength(Key));
}
catch
{
return -1;
}
}
#endregion
#region ------------------------Set 操作-----------------------
///
/// 增加一条数据到Set集合
///
/// 键
/// 值
///
public bool SetAdd(string Key, string Value)
{
try
{
return Do(db => db.SetAdd(Key, Value));
}
catch
{
return false;
}
}
///
/// 增加多条数据到Set集合
///
/// 键
/// 值集合
///
public long SetAdd(string Key, List Value)
{
try
{
return Do(db => db.SetAdd(Key, ListToRedisValue(Value)));
}
catch
{
return -1;
}
}
///
/// 将多个Set集合进行运算操作,返回运算后的集合
///
/// 运算标识,0:并集去重,1:交集,2:差集
/// 键集合
///
public List SetCombine(int Operation, List 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();
}
}
///
/// 将2个Set集合进行运算操作,返回运算后的集合
///
/// 运算标识,0:并集,1:交集,2:差集
/// 集合1
/// 集合2
///
public List 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();
}
}
///
/// 返回该Set集合的元素数量
///
/// 键
///
public long SetLength(string Key)
{
try
{
return Do(db => db.SetLength(Key));
}
catch
{
return -1;
}
}
///
/// 获取该Set集合所有元素
///
/// 键
///
public List SetMembers(string Key)
{
try
{
return RedisValueToList(Do(db => db.SetMembers(Key)));
}
catch
{
return new List();
}
}
///
/// 删除Set集合中的某个元素
///
/// 键
/// 值
///
public bool SetRemove(string Key, string Value)
{
try
{
return Do(db => db.SetRemove(Key, Value));
}
catch
{
return false;
}
}
///
/// 批量删除Set集合中的元素
///
/// 键
/// 值集合
///
public long SetRemove(string Key, List Value)
{
try
{
return Do(db => db.SetRemove(Key, ListToRedisValue(Value)));
}
catch
{
return -1;
}
}
#endregion
#region --------------------SortedSet 操作--------------------
///
/// 增加一条数据到SortedSet集合
///
/// 键
/// 值
/// 分数,作为排序依据
///
public bool SortedSetAdd(string Key, string Value, double OrderValue)
{
try
{
return Do(db => db.SortedSetAdd(Key, Value, OrderValue));
}
catch
{
return false;
}
}
///
/// 增加多条数据到SortedSet集合
///
/// 键
/// 元素集合{ 值,排序值 }
///
public long SortedSetAdd(string Key, Dictionary SortedSetData)
{
try
{
List SortedSetTable = new List();
foreach (var item in SortedSetData.Keys)
{
SortedSetTable.Add(new SortedSetEntry(item, SortedSetData[item]));
}
return Do(db => db.SortedSetAdd(Key, SortedSetTable.ToArray()));
}
catch
{
return -1;
}
}
///
/// 返回该SortedSet集合的元素数量
///
/// 键
///
public long SortedSetLength(string Key)
{
try
{
return Do(db => db.SortedSetLength(Key));
}
catch
{
return -1;
}
}
///
/// 将指定SortedSet的值的分数做加法运算
///
/// 键
/// 值
/// 增加值,可以为负
/// 增长后的值
public double SortedSetIncrement(string Key, string SortedSetValue, double Value)
{
try
{
return Do(db => db.SortedSetIncrement(Key, SortedSetValue, Value));
}
catch
{
return -1;
}
}
///
/// 将指定SortedSet的值的分数做减法运算
///
/// 键
/// 值
/// 减少值,可以为负
/// 减少后的值
public double SortedSetDecrement(string Key, string SortedSetValue, double Value)
{
try
{
return Do(db => db.SortedSetDecrement(Key, SortedSetValue, Value));
}
catch
{
return -1;
}
}
///
/// 返回排序后的元素的值的集合
///
/// 键
/// 起始排名
/// 结束排名
/// 正序或倒序 0:低-高 1:高-低
///
public List 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();
}
}
///
/// 返回排序后的元素集合
///
/// 键
/// 起始排名
/// 结束排名
/// 正序或倒序 0:低-高 1:高-低
///
public Dictionary 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 Result = new Dictionary();
foreach (var item in _SortedSetEntry)
{
Result.Add(item.Element, item.Score);
}
return Result;
}
catch
{
return new Dictionary();
}
}
///
/// 返回指定分数区间的元素的值的集合
///
/// 键
/// 最低分
/// 最高分
/// 正序或倒序 0:低-高 1:高-低
///
public List 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();
}
}
///
/// 返回指定分数区间的元素集合
///
/// 键
/// 最低分
/// 最高分
/// 正序或倒序 0:低-高 1:高-低
///
public Dictionary 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 Result = new Dictionary();
foreach (var item in _SortedSetEntry)
{
Result.Add(item.Element, item.Score);
}
return Result;
}
catch
{
return new Dictionary();
}
}
///
/// 获取某个元素的排名
///
/// 键
/// 值
///
public long? SortedSetRank(string Key, string Value)
{
try
{
return Do(db => db.SortedSetRank(Key, Value)) + 1;
}
catch
{
return -1;
}
}
///
/// 获取某个元素的分数
///
/// 键
/// 值
///
public double? SortedSetScore(string Key, string Value)
{
try
{
return Do(db => db.SortedSetScore(Key, Value));
}
catch
{
return -1;
}
}
///
/// 删除SortedSet集合中某个元素
///
/// 键
/// 值
///
public bool SortedSetRemove(string Key, string Value)
{
try
{
return Do(db => db.SortedSetRemove(Key, Value));
}
catch
{
return false;
}
}
///
/// 批量删除SortedSet集合中的元素
///
/// 键
/// 值集合
///
public long SortedSetRemove(string Key, List Value)
{
try
{
return Do(db => db.SortedSetRemove(Key, ListToRedisValue(Value)));
}
catch
{
return -1;
}
}
///
/// 删除排名区间的元素
///
/// 键
/// 起始排名
/// 结束排名
///
public long SortedSetRemoveRangeByRank(string Key, long Start, long End)
{
try
{
Start--;
End--;
return Do(db => db.SortedSetRemoveRangeByRank(Key, Start, End));
}
catch
{
return -1;
}
}
///
/// 删除分数区间的元素
///
/// 键
/// 最小值
/// 最大值
///
public long SortedSetRemoveRangeByScore(string Key, double Start, double End)
{
try
{
return Do(db => db.SortedSetRemoveRangeByScore(Key, Start, End));
}
catch
{
return -1;
}
}
#endregion
#region ------------------------Key 操作-----------------------
///
/// 删除某个键
///
/// 键
/// 是否删除成功
public bool KeyDelete(string Key)
{
try
{
return Do(db => db.KeyDelete(Key));
}
catch
{
return false;
}
}
///
/// 批量删除键
///
/// 键集合
/// 成功删除的个数
public long KeyDelete(List Keys)
{
try
{
return Do(db => db.KeyDelete(ListToRedisKey(Keys)));
}
catch
{
return -1;
}
}
///
/// 判断键是否存在
///
/// 键
///
public bool KeyExists(string Key)
{
try
{
return Do(db => db.KeyExists(Key));
}
catch
{
return false;
}
}
///
/// 重新命名Key
///
/// 旧的键
/// 新的键
///
public bool KeyRename(string Key, string NewKey)
{
try
{
return Do(db => db.KeyRename(Key, NewKey));
}
catch
{
return false;
}
}
///
/// 设置键的过期时间
///
/// 键
/// 时间长度(值+类型): S:秒 M:分钟 H:小时 D:天 例:100S (100秒)
///
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 ------------------------辅助方法------------------------
///
/// 设置排序参数
///
/// 起始位置
/// 结束位置
/// 排序标识
/// 排序类型
private void SortedSetParm(ref long Start, ref long End, int OrderType, ref Order _Order)
{
Start--;
End--;
_Order = OrderType == 0 ? Order.Ascending : Order.Descending;
}
///
/// List转RedisValue
///
/// List集合
///
private RedisValue[] ListToRedisValue(List List)
{
List _RedisValue = new List();
try
{
for (int i = 0; i < List.Count; i++)
{
_RedisValue.Add(List[i]);
}
return _RedisValue.ToArray();
}
catch
{
return new List().ToArray();
}
}
///
/// RedisValue转List
///
/// RedisValue数组
///
private List RedisValueToList(RedisValue[] _RedisValue)
{
List List = new List();
try
{
for (int i = 0; i < _RedisValue.Length; i++)
{
List.Add(_RedisValue[i]);
}
return List;
}
catch
{
return new List();
}
}
///
/// List转RedisKey
///
/// List集合
///
private RedisKey[] ListToRedisKey(List List)
{
List RedisKey = new List();
try
{
for (int i = 0; i < List.Count; i++)
{
RedisKey.Add(List[i]);
}
return RedisKey.ToArray();
}
catch
{
return new List().ToArray();
}
}
///
/// RedisKey转List
///
/// RedisKey数组
///
private List RedisKeyToList(RedisKey[] _RedisKey)
{
List List = new List();
try
{
for (int i = 0; i < _RedisKey.Length; i++)
{
List.Add(_RedisKey[i]);
}
return List;
}
catch
{
return new List();
}
}
///
/// 执行Redis操作
///
private T Do(Func func)
{
var database = RedisConn.GetDatabase(DbNum);
return func(database);
}
#endregion 辅助方法
#region 其他操作
///
/// 获取当前Redis连接状态
///
///
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;
}
}
///
/// 获取数据库对象
///
///
public IDatabase GetDatabase()
{
return RedisConn.GetDatabase(DbNum);
}
public ITransaction CreateTransaction()
{
return GetDatabase().CreateTransaction();
}
public IServer GetServer(string hostAndPort)
{
return RedisConn.GetServer(hostAndPort);
}
#endregion 其他
#region 发布订阅
///
/// Redis发布订阅 订阅
///
///
///
//public void Subscribe(string subChannel, Action handler = null)
//{
// ISubscriber sub = RedisConn.GetSubscriber();
// sub.Subscribe(subChannel, (channel, message) =>
// {
// if (handler == null)
// {
// Console.WriteLine(subChannel + " 订阅收到消息:" + message);
// }
// else
// {
// handler(channel, message);
// }
// });
//}
///
/// Redis发布订阅 发布
///
///
///
///
///
//public long Publish(string channel, T msg)
//{
// ISubscriber sub = RedisConn.GetSubscriber();
// return sub.Publish(channel, (msg));
//}
///
/// Redis发布订阅 取消订阅
///
///
//public void Unsubscribe(string channel)
//{
// ISubscriber sub = RedisConn.GetSubscriber();
// sub.Unsubscribe(channel);
//}
///
/// Redis发布订阅 取消全部订阅
///
//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
{
///
/// 存放Redis操作对象的公共类
///
public static class RedisCmd
{
///
/// Redis操作对象
///
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");