/***
* Title:"数据采集" 项目
* 主题:Redis帮助类
* Description:
* 功能:
* 1、设置连接字符串、选择数据库、获取到连接状态
* 2、给键添加前缀
* 3、String操作
* 【同步(①保存单个键值对)(②根据键获取到对应的值)(③同时保存多个键值对)(④存储一个对象)(⑤获取一个对象)】
*
* 【异步(①保存单个键值对)(②根据键获取到对应的值)(③同时保存多个键值对)(④存储一个对象)(⑤获取一个对象)】
* 4、Hash操作
* 【同步(①判断单个键值对是否存在Hash中)(②从Hash中移除单个键值对)(③从Hash中同时移除单个键对应的多个字段列表)(④在Hash中指定值)
* (⑤在Hash中同时添加单个键指定的多个字段列表)(⑥在Hash中获取单个键、字段对应的值)(⑦在Hash中同时获取单个键对应的指定字段)
* (⑧在Hash中获取单个键对应的所有字段)(⑨在Hash中获取单个键对应的所有值)(⑩在Hash中给单个键的单个字段添加一个对象值)(⑩①在Hash中获取单个键单个字段对应的对象值)】
*
* 【异步(①判断单个键值对是否存在Hash中)(②从Hash中移除单个键值对)(③从Hash中同时移除单个键对应的多个字段列表)(④在Hash中指定值)
* (⑤在Hash中同时添加单个键指定的多个字段列表)(⑥在Hash中获取单个键、字段对应的值)(⑦在Hash中同时获取单个键对应的指定字段)
* (⑧在Hash中获取单个键对应的所有字段)(⑨在Hash中获取单个键对应的所有值)(⑩在Hash中给单个键的单个字段添加一个对象值)(⑩①在Hash中获取单个键单个字段对应的对象值)】
* 5、List操作
* 【同步(①移除并返回列表中该键对应的第一个元素)(②移除并返回列表中该键对应的最后一个元素)(③移除列表中指定键与该值相同的元素)
* (④在列表尾部插入值。如果键不存在,先创建再插入值)(⑤在列表头部插入值。如果键不存在,先创建再插入值)(⑥返回列表上该键的长度,如果不存在,返回 0)
* (⑦返回在该列表上键所对应的起止点元素)(⑧移除并返回存储在该键列表的第一个元素对象)(⑨移除并返回存储在该键列表的最后一个元素对象)
* (⑩在列表尾部插入值。如果键不存在,先创建再插入值)(⑩①在列表头部插入值。如果键不存在,先创建再插入值)】
*
* 【异步(①移除并返回列表中该键对应的第一个元素)(②移除并返回列表中该键对应的最后一个元素)(③移除列表中指定键与该值相同的元素)
* (④在列表尾部插入值。如果键不存在,先创建再插入值)(⑤在列表头部插入值。如果键不存在,先创建再插入值)(⑥返回列表上该键的长度,如果不存在,返回 0)
* (⑦返回在该列表上键所对应的起止点元素)(⑧移除并返回存储在该键列表的第一个元素对象)(⑨移除并返回存储在该键列表的最后一个元素对象)
* (⑩在列表尾部插入值。如果键不存在,先创建再插入值)(⑩①在列表头部插入值。如果键不存在,先创建再插入值)】
* 6、SortedSet操作
* 【同步(① SortedSet 新增)(②在有序集合中返回指定范围的元素,默认情况下从低到高)(③返回有序集合的元素个数)(④返回有序集合的元素个数)
* (⑤SortedSet 新增)(⑥增量的得分排序的集合中的成员存储键值键按增量)】
*
* 【异步(① SortedSet 新增)(②在有序集合中返回指定范围的元素,默认情况下从低到高)(③返回有序集合的元素个数)(④返回有序集合的元素个数)
* (⑤SortedSet 新增)(⑥增量的得分排序的集合中的成员存储键值键按增量)】
* 7、Key操作
* 【同步(①删除指定Key)(②删除指定Key列表)(③检查Key是否存在)(④重命名Key)(⑤设置Key的时间)】
*
* 【异步(①删除指定Key)(②删除指定Key列表)(③检查Key是否存在)(④重命名Key)(⑤设置Key的时间)】
* 8、发布订阅
* 【同步(①订阅)(②发布)】
*
* 【异步(①订阅)(②发布)】
*
* Date:2021
* Version:0.1版本
* Author:Coffee
* Modify Recoder:
*/
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
public class RedisHelper
{
#region 基础参数
//连接字符串
private readonly string _ConnectStr;
//连接的Redis对象
private static IConnectionMultiplexer _ConnMultiplexer;
//锁
private static readonly object _Locker = new object();
//数据库
private IDatabase _DB;
#endregion
#region 公有方法
///
/// 构造函数
///
/// Redis的连接字符串
public RedisHelper()
{
string connStr= ConfigurationManager.AppSettings["RedisConnStr"];
if (!string.IsNullOrEmpty(connStr))
{
_ConnectStr = connStr;
//获取到连接对象
GetConnectRedisMultiplexer();
//添加注册事件
AddRegisterEvent();
SelectDB(0);
}
}
///
/// 选择数据库
///
/// 数据库编号(默认是编号0的数据库)
public void SelectDB(int db = 0)
{
_DB = _ConnMultiplexer.GetDatabase(db);
}
///
/// 获取到连接状态
///
public bool ConnetStatus
{
get
{
if (_ConnMultiplexer != null)
{
return _ConnMultiplexer.IsConnected;
}
else
{
return false;
}
}
}
///
/// 给键添加前缀
///
/// 前缀名称
/// 键名称
/// 返回添加前缀后的键
public string AddPrefixOfKey(string prefixName, string keyName)
{
string str = $"{prefixName}:{keyName}";
return str;
}
//序列化类型
public enum SerializeType
{
Binary, //二进制
Json, //Json
}
#region String 操作
#region 同步方式
///
/// 保存单个键值对字符串(如果 key 已存在,则覆盖值)
///
/// 键
/// 值
/// 时间间隔
/// 返回结果(true表示成功)
public bool SetString(string redisKey, string redisValue, TimeSpan? expiry = null)
{
if (ConnetStatus)
{
return _DB.StringSet(redisKey, redisValue, expiry);
}
else
{
return false;
}
}
///
/// 获取键对应值字符串
///
/// 键
/// 时间间隔
/// 返回结果(true表示成功)
public string GetString(string redisKey, TimeSpan? expiry = null)
{
if (ConnetStatus)
{
return _DB.StringGet(redisKey);
}
else
{
return null;
}
}
///
/// 保存多个多个键值对字符串
///
/// 键值对容器
/// 返回结果(true表示成功)
public bool SetString(IEnumerable> keyValuePairs)
{
if (ConnetStatus)
{
var pairs = keyValuePairs.Select(x => new KeyValuePair(x.Key, x.Value));
return _DB.StringSet(pairs.ToArray());
}
else
{
return false;
}
}
///
/// 存储一个对象(该对象会被序列化保存)
///
/// 键
/// 值(会被序列化)
/// 时间间隔
/// 序列化类型(默认序列化为Json)
/// 返回结果(true表示成功)
public bool SetObjString(string redisKey, T redisValue, TimeSpan? expiry = null,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
var binaryValue = Serialize(redisValue);
return _DB.StringSet(redisKey, binaryValue, expiry);
case SerializeType.Json:
var jsonValue = SerializeJson(redisValue);
return _DB.StringSet(redisKey, jsonValue, expiry);
default:
return false;
}
}
else
{
return false;
}
}
///
/// 获取一个对象(会进行反序列化)
///
/// 键
///
/// 序列化类型(默认序列化为Json)
/// 返回结果(true表示成功)
public T GetObjString(string redisKey, TimeSpan? expiry = null,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(_DB.StringGet(redisKey));
case SerializeType.Json:
return DeserializeJson(_DB.StringGet(redisKey));
default:
return default(T);
}
}
else
{
return default(T);
}
}
#endregion
#region 异步方式
///
/// 保存一个键值对字符串(异步方式)
///
/// 键
/// 值
/// 时间间隔
/// 返回结果(true表示成功)
public async Task SetStringOfAsync(string redisKey, string redisValue, TimeSpan? expiry = null)
{
if (ConnetStatus)
{
return await _DB.StringSetAsync(redisKey, redisValue, expiry);
}
else
{
return false;
}
}
///
/// 获取单个值
///
/// 键
/// 值
/// 时间间隔
/// 返回结果(true表示成功)
public async Task GetStringOfAsync(string redisKey, TimeSpan? expiry = null)
{
if (ConnetStatus)
{
return await _DB.StringGetAsync(redisKey);
}
else
{
return null;
}
}
///
/// 保存一组字符串值
///
/// 键值对容器
/// 返回结果(true表示成功)
public async Task SetStringOfAsync(IEnumerable> keyValuePairs)
{
if (ConnetStatus)
{
var pairs = keyValuePairs.Select(x => new KeyValuePair(x.Key, x.Value));
return await _DB.StringSetAsync(pairs.ToArray());
}
else
{
return false;
}
}
///
/// 存储一个对象(该对象会被序列化保存)
///
/// 键
/// 值
/// 间隔时间
/// 序列化类型(默认序列化为Json)
/// 返回结果(true表示成功)
public async Task SetObjStringOfAsync(string redisKey, T redisValue, TimeSpan? expiry = null,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
var binaryValue = Serialize(redisValue);
return await _DB.StringSetAsync(redisKey, binaryValue, expiry);
case SerializeType.Json:
var jsonValue = SerializeJson(redisValue);
return await _DB.StringSetAsync(redisKey, jsonValue, expiry);
default:
break;
}
return false;
}
else
{
return false;
}
}
///
/// 获取一个对象(会进行反序列化)
///
/// 键
/// 间隔时间
/// 序列化类型(默认序列化为Json)
/// 返回结果(true表示成功)
public async Task GetObjStringOfAsync(string redisKey, TimeSpan? expiry = null,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(await _DB.StringGetAsync(redisKey));
case SerializeType.Json:
return DeserializeJson(await _DB.StringGetAsync(redisKey));
default:
break;
}
return default(T);
}
else
{
return default(T);
}
}
#endregion
#endregion
#region Hash 操作
#region 同步方式
///
/// 判断该字段是否存在hash中
///
/// 键
/// 字段
/// 返回结果(true:表示成功)
public bool ExistsHash(string redisKey, string hashField)
{
if (ConnetStatus)
{
return _DB.HashExists(redisKey, hashField);
}
else
{
return false;
}
}
///
/// 从 hash 中移除指定字段
///
/// 键
/// 字段
/// 返回结果(true:表示成功)
public bool DeleteHash(string redisKey, string hashField)
{
if (ConnetStatus)
{
return _DB.HashDelete(redisKey, hashField);
}
else
{
return false;
}
}
///
/// 从 hash 中移除指定字段
///
/// 键
/// 字段
/// 返回结果(-1:表示失败)
public long DeleteHash(string redisKey, IEnumerable hashFields)
{
if (ConnetStatus)
{
var fields = hashFields.Select(x => (RedisValue)x);
return _DB.HashDelete(redisKey, fields.ToArray());
}
else
{
return -1;
}
}
///
/// 在 hash 设定值
///
/// 键
/// 字段
/// 值
/// 返回结果(true:表示成功)
public bool SetHash(string redisKey, string hashField, string value)
{
if (ConnetStatus)
{
return _DB.HashSet(redisKey, hashField, value);
}
else
{
return false;
}
}
///
/// 在 hash 中设定值
///
/// 键
/// 字段容器
public void SetHash(string redisKey, IEnumerable> hashFields)
{
if (ConnetStatus)
{
var entries = hashFields.Select(x => new HashEntry(x.Key, x.Value));
_DB.HashSet(redisKey, entries.ToArray());
}
}
///
/// 在 hash 中获取值
///
/// 键
/// 字段
/// 返回结果
public string GetHash(string redisKey, string hashField)
{
if (ConnetStatus)
{
return _DB.HashGet(redisKey, hashField);
}
else
{
return null;
}
}
///
/// 在hash获取值
///
/// 键
/// 字段
/// 返回结果
public IEnumerable GetHash(string redisKey, IEnumerable hashFields)
{
if (ConnetStatus)
{
var fields = hashFields.Select(x => (RedisValue)x);
return ConvertStrings(_DB.HashGet(redisKey, fields.ToArray()));
}
else
{
return null;
}
}
///
/// 从 hash 返回所有的字段值
///
/// 键
/// 返回结果
public IEnumerable HashKeys(string redisKey)
{
if (ConnetStatus)
{
return ConvertStrings(_DB.HashKeys(redisKey));
}
else
{
return null;
}
}
///
/// 根据键获取hash中的所有值
///
/// 键
/// 返回hash结果
public IEnumerable HashValues(string redisKey)
{
if (ConnetStatus)
{
return ConvertStrings(_DB.HashValues(redisKey));
}
else
{
return null;
}
}
///
/// 在 hash 设定值(序列化)
///
/// 键
/// 字段
/// 值
/// 序列化的类型(默认是Json)
/// 返回结果(true:表示成功)
public bool SetObjHash(string redisKey, string hashField, T redisValue,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
var binaryValue = Serialize(redisValue);
return _DB.HashSet(redisKey, hashField, binaryValue);
case SerializeType.Json:
var jsonValue = SerializeJson(redisValue);
return _DB.HashSet(redisKey, hashField, jsonValue);
default:
return false;
}
}
else
{
return false;
}
}
///
/// 在 hash 中获取值(反序列化)
///
///
///
/// 序列化的类型(默认是Json)
///
public T GetObjHash(string redisKey, string hashField,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(_DB.HashGet(redisKey, hashField));
case SerializeType.Json:
return DeserializeJson(_DB.HashGet(redisKey, hashField));
default:
return default(T);
}
}
else
{
return default(T);
}
}
#endregion
#region 异步方式
///
/// 判断该字段是否存在hash中(异步方式)
///
/// 键
/// 字段
/// 返回结果(true:表示存在)
public async Task ExistsHashOfAsync(string redisKey, string hashField)
{
if (ConnetStatus)
{
return await _DB.HashExistsAsync(redisKey, hashField);
}
else
{
return false;
}
}
///
/// 从hash中移除指定字段
///
/// 键
/// 字段
/// 返回结果(true:表示成功)
public async Task DeleteHashOfAsync(string redisKey, string hashField)
{
if (ConnetStatus)
{
return await _DB.HashDeleteAsync(redisKey, hashField);
}
else
{
return false;
}
}
///
/// 从hash中移除指定字段
///
/// 键
/// 字段
/// 返回删除结果(-1 表示失败)
public async Task DeleteHashOfAsync(string redisKey, IEnumerable hashFields)
{
if (ConnetStatus)
{
var fields = hashFields.Select(x => (RedisValue)x);
return await _DB.HashDeleteAsync(redisKey, fields.ToArray());
}
else
{
return -1;
}
}
///
/// 在 hash 设定值
///
/// 键
/// 字段
/// 值
/// 返回结果(true:表示成功)
public async Task SetHashOfAsync(string redisKey, string hashField, string value)
{
if (ConnetStatus)
{
return await _DB.HashSetAsync(redisKey, hashField, value);
}
else
{
return false;
}
}
///
/// 在 hash 中设定值
///
///
///
public async Task SetHashOfAsync(string redisKey, IEnumerable> hashFields)
{
if (ConnetStatus)
{
var entries = hashFields.Select(x => new HashEntry(x.Key, x.Value));
await _DB.HashSetAsync(redisKey, entries.ToArray());
}
else
{
return;
}
}
///
/// 在 hash 中获取值
///
/// 键
/// 字段
/// 返回结果
public async Task GetHashOfAsync(string redisKey, string hashField)
{
if (ConnetStatus)
{
return await _DB.HashGetAsync(redisKey, hashField);
}
else
{
return null;
}
}
///
/// 在 hash 中获取值
///
/// 键
/// 字段
/// 值
/// 返回结果
public async Task> GetHashOfAsync(string redisKey, IEnumerable hashFields,
string value)
{
if (ConnetStatus)
{
var fields = hashFields.Select(x => (RedisValue)x);
return ConvertStrings(await _DB.HashGetAsync(redisKey, fields.ToArray()));
}
else
{
return null;
}
}
///
/// 从 hash 返回所有的字段值
///
/// 键
/// 返回对应的hash字段值
public async Task> HashKeysOfAsync(string redisKey)
{
if (ConnetStatus)
{
return ConvertStrings(await _DB.HashKeysAsync(redisKey));
}
else
{
return null;
}
}
///
/// 返回 hash 中的所有值
///
/// 键
/// 返回hash中的所有值
public async Task> HashValuesAsync(string redisKey)
{
if (ConnetStatus)
{
return ConvertStrings(await _DB.HashValuesAsync(redisKey));
}
else
{
return null;
}
}
///
/// 在 hash 设定值(序列化)
///
/// 键
/// 字段
/// 值
/// 序列化的类型(默认是Json)
/// 返回结果(true:表示成功)
public async Task SetObjHashAsync(string redisKey, string hashField, T value,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
var binaryValue = Serialize(value);
return await _DB.HashSetAsync(redisKey, hashField, binaryValue);
case SerializeType.Json:
var jsonValue = SerializeJson(value);
return await _DB.HashSetAsync(redisKey, hashField, jsonValue);
default:
return false;
}
}
else
{
return false;
}
}
///
/// 在 hash 中获取值(反序列化)
///
///
///
/// 序列化的类型(默认是Json)
///
public async Task GetObjHashAsync(string redisKey, string hashField,
SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(await _DB.HashGetAsync(redisKey, hashField));
case SerializeType.Json:
return DeserializeJson(await _DB.HashGetAsync(redisKey, hashField));
default:
return default(T);
}
}
else
{
return default(T);
}
}
#endregion
#endregion
#region List 操作
#region 同步方式
///
/// 移除并返回存储在该键列表的第一个元素
///
/// 键
///
public string PopFirtKeyOfList(string redisKey)
{
if (ConnetStatus)
{
return _DB.ListLeftPop(redisKey);
}
else
{
return null;
}
}
///
/// 移除并返回存储在该键列表的最后一个元素
///
/// 键
///
public string PopLastKeyOfList(string redisKey)
{
if (ConnetStatus)
{
return _DB.ListRightPop(redisKey);
}
else
{
return null;
}
}
///
/// 移除列表指定键上与该值相同的元素
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public long PopSameKeyOfList(string redisKey, string redisValue)
{
if (ConnetStatus)
{
return _DB.ListRemove(redisKey, redisValue);
}
else
{
return -1;
}
}
///
/// 在列表尾部插入值。如果键不存在,先创建再插入值
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public long PushKeyOfListLast(string redisKey, string redisValue)
{
if (ConnetStatus)
{
return _DB.ListRightPush(redisKey, redisValue);
}
else
{
return -1;
}
}
///
/// 在列表头部插入值。如果键不存在,先创建再插入值
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public long PushKeyOfListFirst(string redisKey, string redisValue)
{
if (ConnetStatus)
{
return _DB.ListLeftPush(redisKey, redisValue);
}
else
{
return -1;
}
}
///
/// 返回列表上该键的长度,如果不存在,返回 0
///
/// 键
/// 返回结果(-1 表示失败)
public long GetKeyLengthOfList(string redisKey)
{
if (ConnetStatus)
{
return _DB.ListLength(redisKey);
}
else
{
return -1;
}
}
///
/// 返回在该列表上键所对应的元素
///
/// 键
/// 起始点
/// 停止点
///
public IEnumerable ListRange(string redisKey, long start = 0L, long stop = -1L)
{
if (ConnetStatus)
{
return ConvertStrings(_DB.ListRange(redisKey, start, stop));
}
else
{
return null;
}
}
///
/// 移除并返回存储在该键列表的第一个元素对象
///
/// 键
/// 序列化类型(默认是Json)
/// 返回反序列化后对象
public T PopFirstKeyObjOfList(string redisKey, SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(_DB.ListLeftPop(redisKey));
case SerializeType.Json:
return DeserializeJson(_DB.ListLeftPop(redisKey));
default:
return default(T);
}
}
else
{
return default(T);
}
}
///
/// 移除并返回存储在该键列表的最后一个元素对象
///
/// 键
/// 序列化类型(默认是Json)
/// 返回反序列化后的对象
public T PopLastKeyObjOfList(string redisKey, SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(_DB.ListRightPop(redisKey));
case SerializeType.Json:
return DeserializeJson(_DB.ListRightPop(redisKey));
default:
return default(T);
}
}
else
{
return default(T);
}
}
///
/// 在列表尾部插入值。如果键不存在,先创建再插入值
///
///
///
/// 返回结果(-1 表示失败)
public long PushKeyOfListLast(string redisKey, T redisValue)
{
if (ConnetStatus)
{
return _DB.ListRightPush(redisKey, Serialize(redisValue));
}
else
{
return -1;
}
}
///
/// 在列表头部插入值。如果键不存在,先创建再插入值
///
///
///
/// 返回结果(-1 表示失败)
public long PushKeyOfListHead(string redisKey, T redisValue)
{
if (ConnetStatus)
{
return _DB.ListLeftPush(redisKey, Serialize(redisValue));
}
else
{
return -1;
}
}
#endregion
#region 异步方式
///
/// 移除并返回存储在该键列表的第一个元素
///
///
///
public async Task PopFirtKeyOfListAsync(string redisKey)
{
if (ConnetStatus)
{
return await _DB.ListLeftPopAsync(redisKey);
}
else
{
return null;
}
}
///
/// 移除并返回存储在该键列表的最后一个元素
///
/// 键
///
public async Task PopLastKeyOfListAsync(string redisKey)
{
if (ConnetStatus)
{
return await _DB.ListRightPopAsync(redisKey);
}
else
{
return null;
}
}
///
/// 移除列表指定键上与该值相同的元素
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public async Task PopSameKeyOfListAsync(string redisKey, string redisValue)
{
if (ConnetStatus)
{
return await _DB.ListRemoveAsync(redisKey, redisValue);
}
else
{
return -1;
}
}
///
/// 在列表尾部插入值。如果键不存在,先创建再插入值
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public async Task PushKeyOfListLastAsync(string redisKey, string redisValue)
{
if (ConnetStatus)
{
return await _DB.ListRightPushAsync(redisKey, redisValue);
}
else
{
return -1;
}
}
///
/// 在列表头部插入值。如果键不存在,先创建再插入值
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public async Task PushKeyOfListHeadAsync(string redisKey, string redisValue)
{
if (ConnetStatus)
{
return await _DB.ListLeftPushAsync(redisKey, redisValue);
}
else
{
return -1;
}
}
///
/// 返回列表上该键的长度,如果不存在,返回 0
///
/// 键
/// 返回结果(-1 表示失败)
public async Task GetKeyLengthOfListAsync(string redisKey)
{
if (ConnetStatus)
{
return await _DB.ListLengthAsync(redisKey);
}
else
{
return -1;
}
}
///
/// 返回在该列表上键所对应的元素
///
/// 键
///
///
///
public async Task> ListRangeAsync(string redisKey, long start = 0L, long stop = -1L)
{
if (ConnetStatus)
{
var query = await _DB.ListRangeAsync(redisKey, start, stop);
return query.Select(x => x.ToString());
}
else
{
return null;
}
}
///
/// 移除并返回存储在该键列表的第一个元素对象
///
///
/// 序列化类型(默认是Json)
/// 返回反序列化后的对象
public async Task PopFirstKeyObjOfListAsync(string redisKey, SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(await _DB.ListLeftPopAsync(redisKey));
case SerializeType.Json:
return DeserializeJson(await _DB.ListLeftPopAsync(redisKey));
default:
return default(T);
}
}
else
{
return default(T);
}
}
///
/// 移除并返回存储在该键列表的最后一个元素对象
///
/// 键
/// 序列化类型(默认是Json)
/// 返回反序列化后的对象
public async Task PopLastKeyObjOfListAsync(string redisKey, SerializeType serializeType = SerializeType.Json)
{
if (ConnetStatus)
{
switch (serializeType)
{
case SerializeType.Binary:
return Deserialize(await _DB.ListRightPopAsync(redisKey));
case SerializeType.Json:
return DeserializeJson(await _DB.ListRightPopAsync(redisKey));
default:
return default(T);
}
}
else
{
return default(T);
}
}
///
/// 在列表尾部插入值。如果键不存在,先创建再插入值
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public async Task PushKeyOfListLastAsync(string redisKey, T redisValue)
{
if (ConnetStatus)
{
return await _DB.ListRightPushAsync(redisKey, Serialize(redisValue));
}
else
{
return -1;
}
}
///
/// 在列表头部插入值。如果键不存在,先创建再插入值
///
/// 键
/// 值
/// 返回结果(-1 表示失败)
public async Task PushKeyOfListHeadAsync(string redisKey, T redisValue)
{
if (ConnetStatus)
{
return await _DB.ListLeftPushAsync(redisKey, Serialize(redisValue));
}
else
{
return -1;
}
}
#endregion
#endregion
#region SortedSet 操作
#region 同步方式
///
/// SortedSet 新增
///
/// 键
///
///
///
public bool SortedSetAdd(string redisKey, string member, double score)
{
if (ConnetStatus)
{
return _DB.SortedSetAdd(redisKey, member, score);
}
else
{
return false;
}
}
///
/// 在有序集合中返回指定范围的元素,默认情况下从低到高
///
///
///
///
///
///
public IEnumerable SortedSetRangeByRank(string redisKey, long start = 0L, long stop = -1L,
OrderType order = OrderType.Asc)
{
if (ConnetStatus)
{
return _DB.SortedSetRangeByRank(redisKey, start, stop, (Order)order).Select(x => x.ToString());
}
else
{
return null;
}
}
///
/// 返回有序集合的元素个数
///
///
/// 返回结果(-1 表示失败)
public long SortedSetLength(string redisKey)
{
if (ConnetStatus)
{
return _DB.SortedSetLength(redisKey);
}
else
{
return -1;
}
}
///
/// 返回有序集合的元素个数
///
///
///
/// 返回结果(true:表示成功)
public bool SortedSetLength(string redisKey, string memebr)
{
if (ConnetStatus)
{
return _DB.SortedSetRemove(redisKey, memebr);
}
else
{
return false;
}
}
///
/// SortedSet 新增
///
///
///
///
/// 返回结果(true:表示成功)
public bool SortedSetAdd(string redisKey, T member, double score)
{
if (ConnetStatus)
{
var json = Serialize(member);
return _DB.SortedSetAdd(redisKey, json, score);
}
else
{
return false;
}
}
///
/// 增量的得分排序的集合中的成员存储键值键按增量
///
///
///
///
/// 返回结果(-1 表示失败)
public double SortedSetIncrement(string redisKey, string member, double value = 1)
{
if (ConnetStatus)
{
return _DB.SortedSetIncrement(redisKey, member, value);
}
else
{
return -1;
}
}
#endregion
#region 异步方式
///
/// SortedSet 新增
///
///
///
///
/// 返回结果(true:表示成功)
public async Task SortedSetAddAsync(string redisKey, string member, double score)
{
if (ConnetStatus)
{
return await _DB.SortedSetAddAsync(redisKey, member, score);
}
else
{
return false;
}
}
///
/// 在有序集合中返回指定范围的元素,默认情况下从低到高。
///
///
///
public async Task> SortedSetRangeByRankAsync(string redisKey)
{
if (ConnetStatus)
{
return ConvertStrings(await _DB.SortedSetRangeByRankAsync(redisKey));
}
else
{
return null;
}
}
///
/// 返回有序集合的元素个数
///
///
/// 返回结果(-1 表示失败)
public async Task SortedSetLengthAsync(string redisKey)
{
if (ConnetStatus)
{
return await _DB.SortedSetLengthAsync(redisKey);
}
else
{
return -1;
}
}
///
/// 返回有序集合的元素个数
///
///
///
/// 返回结果(true:表示成功)
public async Task SortedSetRemoveAsync(string redisKey, string memebr)
{
if (ConnetStatus)
{
return await _DB.SortedSetRemoveAsync(redisKey, memebr);
}
else
{
return false;
}
}
///
/// SortedSet 新增
///
///
///
///
///
public async Task SortedSetAddAsync(string redisKey, T member, double score)
{
if (ConnetStatus)
{
var json = Serialize(member);
return await _DB.SortedSetAddAsync(redisKey, json, score);
}
else
{
return false;
}
}
///
/// 增量的得分排序的集合中的成员存储键值键按增量
///
///
///
///
/// 返回结果(-1 表示失败)
public async Task SortedSetIncrementAsync(string redisKey, string member, double value = 1)
{
if (ConnetStatus)
{
return await _DB.SortedSetIncrementAsync(redisKey, member, value);
}
else
{
return -1;
}
}
#endregion
///
/// Redis 排序类型
///
public enum OrderType
{
Asc,
Desc
}
#endregion
#region Key 操作
#region 同步方式
///
/// 删除指定Key
///
/// 键
/// 返回结果(true:表示成功)
public bool DeleteKey(string redisKey)
{
if (ConnetStatus)
{
return _DB.KeyDelete(redisKey);
}
else
{
return false;
}
}
///
/// 删除指定Key列表
///
/// 键容器
/// 移除指定键的数量(-1:表示失败)
public long DeleteKey(IEnumerable redisKeys)
{
if (ConnetStatus)
{
var keys = redisKeys.Select(x => (RedisKey)x);
return _DB.KeyDelete(keys.ToArray());
}
else
{
return -1;
}
}
///
/// 检查Key是否存在
///
/// 键
/// 返回结果(true:表示成功)
public bool ExistsKey(string redisKey)
{
if (ConnetStatus)
{
return _DB.KeyExists(redisKey);
}
else
{
return false;
}
}
///
/// 重命名Key
///
/// 原来的键
/// 新的键名
/// 返回结果(true:表示成功)
public bool RenameKey(string redisKey, string redisNewKey)
{
if (ConnetStatus)
{
return _DB.KeyRename(redisKey, redisNewKey);
}
else
{
return false;
}
}
///
/// 设置 Key 的时间
///
/// 键
/// 时间间隔
/// 返回结果(true:表示成功)
public bool SetKeyExpire(string redisKey, TimeSpan? expiry)
{
if (ConnetStatus)
{
return _DB.KeyExpire(redisKey, expiry);
}
else
{
return false;
}
}
#endregion
#region 异步方式
///
/// 移除指定 Key
///
/// 键
/// 返回结果(true:表示成功)
public async Task DeleteKeyAsync(string redisKey)
{
if (ConnetStatus)
{
return await _DB.KeyDeleteAsync(redisKey);
}
else
{
return false;
}
}
///
/// 删除指定 Key 列表
///
/// 键
/// 返回结果(-1 表示失败)
public async Task DeleteKeyAsync(IEnumerable redisKeys)
{
if (ConnetStatus)
{
var keys = redisKeys.Select(x => (RedisKey)x);
return await _DB.KeyDeleteAsync(keys.ToArray());
}
else
{
return -1;
}
}
///
/// 检查 Key 是否存在
///
/// 键
/// 返回结果(true:表示成功)
public async Task ExistsKeyAsync(string redisKey)
{
if (ConnetStatus)
{
return await _DB.KeyExistsAsync(redisKey);
}
else
{
return false;
}
}
///
/// 重命名 Key
///
/// 旧的键名称
/// 新的键名称
/// 返回结果(true:表示成功)
public async Task RenameKeyAsync(string redisKey, string redisNewKey)
{
if (ConnetStatus)
{
return await _DB.KeyRenameAsync(redisKey, redisNewKey);
}
else
{
return false;
}
}
///
/// 设置 Key 的时间
///
/// 键
/// 间隔时间
/// 返回结果(true:表示成功)
public async Task SetKeyExpireAsync(string redisKey, TimeSpan? expiry)
{
if (ConnetStatus)
{
return await _DB.KeyExpireAsync(redisKey, expiry);
}
else
{
return false;
}
}
#endregion
#endregion
#region 发布订阅
#region 同步方式
///
/// 订阅
///
///
///
public void Subscribe(RedisChannel channel, Action handle)
{
var sub = _ConnMultiplexer.GetSubscriber();
sub.Subscribe(channel, handle);
}
///
/// 发布
///
///
///
///
public long Publish(RedisChannel channel, RedisValue message)
{
var sub = _ConnMultiplexer.GetSubscriber();
return sub.Publish(channel, message);
}
///
/// 发布(使用序列化)
///
///
///
///
///
public long Publish(RedisChannel channel, T message)
{
var sub = _ConnMultiplexer.GetSubscriber();
return sub.Publish(channel, Serialize(message));
}
#endregion
#region 异步方式
///
/// 订阅
///
///
///
public async Task SubscribeAsync(RedisChannel channel, Action handle)
{
var sub = _ConnMultiplexer.GetSubscriber();
await sub.SubscribeAsync(channel, handle);
}
///
/// 发布
///
///
///
///
public async Task PublishAsync(RedisChannel channel, RedisValue message)
{
var sub = _ConnMultiplexer.GetSubscriber();
return await sub.PublishAsync(channel, message);
}
///
/// 发布(使用序列化)
///
///
///
///
///
public async Task PublishAsync(RedisChannel channel, T message)
{
var sub = _ConnMultiplexer.GetSubscriber();
return await sub.PublishAsync(channel, Serialize(message));
}
#endregion
#endregion
#endregion
#region 私有方法
///
/// 获取到连接的Redis对象
///
///
private IConnectionMultiplexer GetConnectRedisMultiplexer()
{
if (_ConnMultiplexer == null || !_ConnMultiplexer.IsConnected)
{
lock (_Locker)
{
if (_ConnMultiplexer == null || !_ConnMultiplexer.IsConnected)
{
_ConnMultiplexer = ConnectionMultiplexer.Connect(_ConnectStr);
}
}
}
return _ConnMultiplexer;
}
#region 注册事件
///
/// 添加注册事件
///
private static void AddRegisterEvent()
{
_ConnMultiplexer.ConnectionRestored += ConnMultiplexer_ConnectionRestored;
_ConnMultiplexer.ConnectionFailed += ConnMultiplexer_ConnectionFailed;
_ConnMultiplexer.ErrorMessage += ConnMultiplexer_ErrorMessage;
_ConnMultiplexer.ConfigurationChanged += ConnMultiplexer_ConfigurationChanged;
_ConnMultiplexer.HashSlotMoved += ConnMultiplexer_HashSlotMoved;
_ConnMultiplexer.InternalError += ConnMultiplexer_InternalError;
_ConnMultiplexer.ConfigurationChangedBroadcast += ConnMultiplexer_ConfigurationChangedBroadcast;
}
///
/// 重新配置广播时(通常意味着主从同步更改)
///
///
///
private static void ConnMultiplexer_ConfigurationChangedBroadcast(object sender, EndPointEventArgs e)
{
Console.WriteLine($"{nameof(ConnMultiplexer_ConfigurationChangedBroadcast)}: {e.EndPoint}");
}
///
/// 发生内部错误时(主要用于调试)
///
///
///
private static void ConnMultiplexer_InternalError(object sender, InternalErrorEventArgs e)
{
Console.WriteLine($"{nameof(ConnMultiplexer_InternalError)}: {e.Exception}");
}
///
/// 更改集群时
///
///
///
private static void ConnMultiplexer_HashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
Console.WriteLine(
$"{nameof(ConnMultiplexer_HashSlotMoved)}: {nameof(e.OldEndPoint)}-{e.OldEndPoint} To {nameof(e.NewEndPoint)}-{e.NewEndPoint}, ");
}
///
/// 配置更改时
///
///
///
private static void ConnMultiplexer_ConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine($"{nameof(ConnMultiplexer_ConfigurationChanged)}: {e.EndPoint}");
}
///
/// 发生错误时
///
///
///
private static void ConnMultiplexer_ErrorMessage(object sender, RedisErrorEventArgs e)
{
Console.WriteLine($"{nameof(ConnMultiplexer_ErrorMessage)}: {e.Message}");
}
///
/// 物理连接失败时
///
///
///
private static void ConnMultiplexer_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine($"{nameof(ConnMultiplexer_ConnectionFailed)}: {e.Exception}");
}
///
/// 建立物理连接时
///
///
///
private static void ConnMultiplexer_ConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine($"{nameof(ConnMultiplexer_ConnectionRestored)}: {e.Exception}");
}
#endregion 注册事件
///
/// 转换为字符串
///
/// 数据类型
/// 数据列表
/// 返回转为字符串后的数据列表
private static IEnumerable ConvertStrings(IEnumerable list) where T : struct
{
if (list == null) throw new ArgumentNullException(nameof(list));
return list.Select(x => x.ToString());
}
///
/// 序列化(二进制)
///
///
///
private static byte[] Serialize(object obj)
{
if (obj == null)
return null;
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, obj);
var data = memoryStream.ToArray();
return data;
}
}
///
/// 反序列化(二进制)
///
///
///
///
private static T Deserialize(byte[] data)
{
if (data == null)
return default(T);
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream(data))
{
var result = (T)binaryFormatter.Deserialize(memoryStream);
return result;
}
}
///
/// 序列化对象为Json字符串
///
/// 实体类型
/// 实体对象
/// 返回序列化的字符串
private static string SerializeJson(T obj)
{
string tmp = null;
if (obj != null)
{
tmp = JsonConvert.SerializeObject(obj);
}
return tmp;
}
///
/// 反序列化Json字符串为对象
///
/// 实体类型
/// 字符串
///
private static T DeserializeJson(string strjson)
{
T tmp = default(T);
try
{
if (!string.IsNullOrEmpty(strjson))
{
tmp = JsonConvert.DeserializeObject(strjson);
}
}
catch (Exception ex)
{
throw;
}
return tmp;
}
#endregion
}//Class_end
}