Redis RedisHelper

1、添加StackExchange.Redis引用

Install-Package StackExchange.Redis -Version 2.0.601

2、封装RedisHelper

using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;namespace RedisDemo
{/// <summary>/// Redis 助手/// </summary>public class RedisHelper{/// <summary>/// 连接字符串/// </summary>private readonly string ConnectionString;/// <summary>/// redis 连接对象/// </summary>private IConnectionMultiplexer _connMultiplexer;/// <summary>/// 默认的 Key 值(用来当作 RedisKey 的前缀)/// </summary>private readonly string DefaultKey;/// <summary>/// 锁/// </summary>private readonly object Locker = new object();/// <summary>/// 数据库/// </summary>private readonly IDatabase _db;/// <summary>/// 获取 Redis 连接对象/// </summary>/// <returns></returns>public IConnectionMultiplexer GetConnectionRedisMultiplexer(){if ((_connMultiplexer == null) || !_connMultiplexer.IsConnected){lock (Locker){if ((_connMultiplexer == null) || !_connMultiplexer.IsConnected)_connMultiplexer = ConnectionMultiplexer.Connect(ConnectionString);}}return _connMultiplexer;}#region 其它public ITransaction GetTransaction(){return _db.CreateTransaction();}#endregion 其它#region 构造函数public RedisHelper(string RedisConnectionString = "localhost", string defaultKey = "redisKey", int DataBaseIndex = 0){ConnectionString = RedisConnectionString;_connMultiplexer = ConnectionMultiplexer.Connect(ConnectionString);DefaultKey = defaultKey;AddRegisterEvent();_db = _connMultiplexer.GetDatabase(DataBaseIndex);}#endregion 构造函数#region String 操作/// <summary>/// 设置 key 并保存字符串(如果 key 已存在,则覆盖值)/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <param name="expiry"></param>/// <returns></returns>public bool StringSet(string redisKey, string redisValue, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);return _db.StringSet(redisKey, redisValue, expiry);}/// <summary>/// 保存多个 Key-value/// </summary>/// <param name="keyValuePairs"></param>/// <returns></returns>public bool StringSet(IEnumerable<KeyValuePair<RedisKey, RedisValue>> keyValuePairs){keyValuePairs =keyValuePairs.Select(x => new KeyValuePair<RedisKey, RedisValue>(AddKeyPrefix(x.Key), x.Value));return _db.StringSet(keyValuePairs.ToArray());}/// <summary>/// 获取字符串/// </summary>/// <param name="redisKey"></param>/// <param name="expiry"></param>/// <returns></returns>public string StringGet(string redisKey, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);return _db.StringGet(redisKey);}/// <summary>/// 存储一个对象(该对象会被序列化保存)/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <param name="expiry"></param>/// <returns></returns>public bool StringSet<T>(string redisKey, T redisValue, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);var json = Serialize(redisValue);return _db.StringSet(redisKey, json, expiry);}/// <summary>/// 获取一个对象(会进行反序列化)/// </summary>/// <param name="redisKey"></param>/// <param name="expiry"></param>/// <returns></returns>public T StringGet<T>(string redisKey, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(_db.StringGet(redisKey));}#region async/// <summary>/// 保存一个字符串值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <param name="expiry"></param>/// <returns></returns>public async Task<bool> StringSetAsync(string redisKey, string redisValue, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);return await _db.StringSetAsync(redisKey, redisValue, expiry);}/// <summary>/// 保存一组字符串值/// </summary>/// <param name="keyValuePairs"></param>/// <returns></returns>public async Task<bool> StringSetAsync(IEnumerable<KeyValuePair<RedisKey, RedisValue>> keyValuePairs){keyValuePairs =keyValuePairs.Select(x => new KeyValuePair<RedisKey, RedisValue>(AddKeyPrefix(x.Key), x.Value));return await _db.StringSetAsync(keyValuePairs.ToArray());}/// <summary>/// 获取单个值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <param name="expiry"></param>/// <returns></returns>public async Task<string> StringGetAsync(string redisKey, string redisValue, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);return await _db.StringGetAsync(redisKey);}/// <summary>/// 存储一个对象(该对象会被序列化保存)/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <param name="expiry"></param>/// <returns></returns>public async Task<bool> StringSetAsync<T>(string redisKey, T redisValue, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);var json = Serialize(redisValue);return await _db.StringSetAsync(redisKey, json, expiry);}/// <summary>/// 获取一个对象(会进行反序列化)/// </summary>/// <param name="redisKey"></param>/// <param name="expiry"></param>/// <returns></returns>public async Task<T> StringGetAsync<T>(string redisKey, TimeSpan? expiry = null){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(await _db.StringGetAsync(redisKey));}#endregion async#endregion String 操作#region Hash 操作/// <summary>/// 判断该字段是否存在 hash 中/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public bool HashExists(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return _db.HashExists(redisKey, hashField);}/// <summary>/// 从 hash 中移除指定字段/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public bool HashDelete(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return _db.HashDelete(redisKey, hashField);}/// <summary>/// 从 hash 中移除指定字段/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public long HashDelete(string redisKey, IEnumerable<RedisValue> hashField){redisKey = AddKeyPrefix(redisKey);return _db.HashDelete(redisKey, hashField.ToArray());}/// <summary>/// 在 hash 设定值/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <param name="value"></param>/// <returns></returns>public bool HashSet(string redisKey, string hashField, string value){redisKey = AddKeyPrefix(redisKey);return _db.HashSet(redisKey, hashField, value);}/// <summary>/// 在 hash 中设定值/// </summary>/// <param name="redisKey"></param>/// <param name="hashFields"></param>public void HashSet(string redisKey, IEnumerable<HashEntry> hashFields){redisKey = AddKeyPrefix(redisKey);_db.HashSet(redisKey, hashFields.ToArray());}/// <summary>/// 在 hash 中获取值/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public RedisValue HashGet(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return _db.HashGet(redisKey, hashField);}/// <summary>/// 在 hash 中获取值/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <param name="value"></param>/// <returns></returns>public RedisValue[] HashGet(string redisKey, RedisValue[] hashField, string value){redisKey = AddKeyPrefix(redisKey);return _db.HashGet(redisKey, hashField);}/// <summary>/// 从 hash 返回所有的字段值/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public IEnumerable<RedisValue> HashKeys(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.HashKeys(redisKey);}/// <summary>/// 返回 hash 中的所有值/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public RedisValue[] HashValues(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.HashValues(redisKey);}/// <summary>/// 在 hash 设定值(序列化)/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <param name="value"></param>/// <returns></returns>public bool HashSet<T>(string redisKey, string hashField, T value){redisKey = AddKeyPrefix(redisKey);var json = Serialize(value);return _db.HashSet(redisKey, hashField, json);}/// <summary>/// 在 hash 中获取值(反序列化)/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public T HashGet<T>(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(_db.HashGet(redisKey, hashField));}#region async/// <summary>/// 判断该字段是否存在 hash 中/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public async Task<bool> HashExistsAsync(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return await _db.HashExistsAsync(redisKey, hashField);}/// <summary>/// 从 hash 中移除指定字段/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public async Task<bool> HashDeleteAsync(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return await _db.HashDeleteAsync(redisKey, hashField);}/// <summary>/// 从 hash 中移除指定字段/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public async Task<long> HashDeleteAsync(string redisKey, IEnumerable<RedisValue> hashField){redisKey = AddKeyPrefix(redisKey);return await _db.HashDeleteAsync(redisKey, hashField.ToArray());}/// <summary>/// 在 hash 设定值/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <param name="value"></param>/// <returns></returns>public async Task<bool> HashSetAsync(string redisKey, string hashField, string value){redisKey = AddKeyPrefix(redisKey);return await _db.HashSetAsync(redisKey, hashField, value);}/// <summary>/// 在 hash 中设定值/// </summary>/// <param name="redisKey"></param>/// <param name="hashFields"></param>public async Task HashSetAsync(string redisKey, IEnumerable<HashEntry> hashFields){redisKey = AddKeyPrefix(redisKey);await _db.HashSetAsync(redisKey, hashFields.ToArray());}/// <summary>/// 在 hash 中获取值/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public async Task<RedisValue> HashGetAsync(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return await _db.HashGetAsync(redisKey, hashField);}/// <summary>/// 在 hash 中获取值/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <param name="value"></param>/// <returns></returns>public async Task<IEnumerable<RedisValue>> HashGetAsync(string redisKey, RedisValue[] hashField, string value){redisKey = AddKeyPrefix(redisKey);return await _db.HashGetAsync(redisKey, hashField);}/// <summary>/// 从 hash 返回所有的字段值/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<IEnumerable<RedisValue>> HashKeysAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.HashKeysAsync(redisKey);}/// <summary>/// 返回 hash 中的所有值/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<IEnumerable<RedisValue>> HashValuesAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.HashValuesAsync(redisKey);}/// <summary>/// 在 hash 设定值(序列化)/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <param name="value"></param>/// <returns></returns>public async Task<bool> HashSetAsync<T>(string redisKey, string hashField, T value){redisKey = AddKeyPrefix(redisKey);var json = Serialize(value);return await _db.HashSetAsync(redisKey, hashField, json);}/// <summary>/// 在 hash 中获取值(反序列化)/// </summary>/// <param name="redisKey"></param>/// <param name="hashField"></param>/// <returns></returns>public async Task<T> HashGetAsync<T>(string redisKey, string hashField){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(await _db.HashGetAsync(redisKey, hashField));}#endregion async#endregion Hash 操作#region List 操作/// <summary>/// 移除并返回存储在该键列表的第一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public string ListLeftPop(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.ListLeftPop(redisKey);}/// <summary>/// 移除并返回存储在该键列表的最后一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public string ListRightPop(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.ListRightPop(redisKey);}/// <summary>/// 移除列表指定键上与该值相同的元素/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public long ListRemove(string redisKey, string redisValue){redisKey = AddKeyPrefix(redisKey);return _db.ListRemove(redisKey, redisValue);}/// <summary>/// 在列表尾部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public long ListRightPush(string redisKey, string redisValue){redisKey = AddKeyPrefix(redisKey);return _db.ListRightPush(redisKey, redisValue);}/// <summary>/// 在列表头部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public long ListLeftPush(string redisKey, string redisValue){redisKey = AddKeyPrefix(redisKey);return _db.ListLeftPush(redisKey, redisValue);}/// <summary>/// 返回列表上该键的长度,如果不存在,返回 0/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public long ListLength(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.ListLength(redisKey);}/// <summary>/// 返回在该列表上键所对应的元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public IEnumerable<RedisValue> ListRange(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.ListRange(redisKey);}/// <summary>/// 移除并返回存储在该键列表的第一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public T ListLeftPop<T>(string redisKey){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(_db.ListLeftPop(redisKey));}/// <summary>/// 移除并返回存储在该键列表的最后一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public T ListRightPop<T>(string redisKey){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(_db.ListRightPop(redisKey));}/// <summary>/// 在列表尾部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public long ListRightPush<T>(string redisKey, T redisValue){redisKey = AddKeyPrefix(redisKey);return _db.ListRightPush(redisKey, Serialize(redisValue));}/// <summary>/// 在列表头部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public long ListLeftPush<T>(string redisKey, T redisValue){redisKey = AddKeyPrefix(redisKey);return _db.ListLeftPush(redisKey, Serialize(redisValue));}#region List-async/// <summary>/// 移除并返回存储在该键列表的第一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<string> ListLeftPopAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.ListLeftPopAsync(redisKey);}/// <summary>/// 移除并返回存储在该键列表的最后一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<string> ListRightPopAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.ListRightPopAsync(redisKey);}/// <summary>/// 移除列表指定键上与该值相同的元素/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public async Task<long> ListRemoveAsync(string redisKey, string redisValue){redisKey = AddKeyPrefix(redisKey);return await _db.ListRemoveAsync(redisKey, redisValue);}/// <summary>/// 在列表尾部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public async Task<long> ListRightPushAsync(string redisKey, string redisValue){redisKey = AddKeyPrefix(redisKey);return await _db.ListRightPushAsync(redisKey, redisValue);}/// <summary>/// 在列表头部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public async Task<long> ListLeftPushAsync(string redisKey, string redisValue){redisKey = AddKeyPrefix(redisKey);return await _db.ListLeftPushAsync(redisKey, redisValue);}/// <summary>/// 返回列表上该键的长度,如果不存在,返回 0/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<long> ListLengthAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.ListLengthAsync(redisKey);}/// <summary>/// 返回在该列表上键所对应的元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<IEnumerable<RedisValue>> ListRangeAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.ListRangeAsync(redisKey);}/// <summary>/// 移除并返回存储在该键列表的第一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<T> ListLeftPopAsync<T>(string redisKey){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(await _db.ListLeftPopAsync(redisKey));}/// <summary>/// 移除并返回存储在该键列表的最后一个元素/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<T> ListRightPopAsync<T>(string redisKey){redisKey = AddKeyPrefix(redisKey);return Deserialize<T>(await _db.ListRightPopAsync(redisKey));}/// <summary>/// 在列表尾部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public async Task<long> ListRightPushAsync<T>(string redisKey, T redisValue){redisKey = AddKeyPrefix(redisKey);return await _db.ListRightPushAsync(redisKey, Serialize(redisValue));}/// <summary>/// 在列表头部插入值。如果键不存在,先创建再插入值/// </summary>/// <param name="redisKey"></param>/// <param name="redisValue"></param>/// <returns></returns>public async Task<long> ListLeftPushAsync<T>(string redisKey, T redisValue){redisKey = AddKeyPrefix(redisKey);return await _db.ListLeftPushAsync(redisKey, Serialize(redisValue));}#endregion List-async#endregion List 操作#region SortedSet 操作/// <summary>/// SortedSet 新增/// </summary>/// <param name="redisKey"></param>/// <param name="member"></param>/// <param name="score"></param>/// <returns></returns>public bool SortedSetAdd(string redisKey, string member, double score){redisKey = AddKeyPrefix(redisKey);return _db.SortedSetAdd(redisKey, member, score);}/// <summary>/// 在有序集合中返回指定范围的元素,默认情况下从低到高。/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public IEnumerable<RedisValue> SortedSetRangeByRank(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.SortedSetRangeByRank(redisKey);}/// <summary>/// 返回有序集合的元素个数/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public long SortedSetLength(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.SortedSetLength(redisKey);}/// <summary>/// 返回有序集合的元素个数/// </summary>/// <param name="redisKey"></param>/// <param name="memebr"></param>/// <returns></returns>public bool SortedSetLength(string redisKey, string memebr){redisKey = AddKeyPrefix(redisKey);return _db.SortedSetRemove(redisKey, memebr);}/// <summary>/// SortedSet 新增/// </summary>/// <param name="redisKey"></param>/// <param name="member"></param>/// <param name="score"></param>/// <returns></returns>public bool SortedSetAdd<T>(string redisKey, T member, double score){redisKey = AddKeyPrefix(redisKey);var json = Serialize(member);return _db.SortedSetAdd(redisKey, json, score);}#region SortedSet-Async/// <summary>/// SortedSet 新增/// </summary>/// <param name="redisKey"></param>/// <param name="member"></param>/// <param name="score"></param>/// <returns></returns>public async Task<bool> SortedSetAddAsync(string redisKey, string member, double score){redisKey = AddKeyPrefix(redisKey);return await _db.SortedSetAddAsync(redisKey, member, score);}/// <summary>/// 在有序集合中返回指定范围的元素,默认情况下从低到高。/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<IEnumerable<RedisValue>> SortedSetRangeByRankAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.SortedSetRangeByRankAsync(redisKey);}/// <summary>/// 返回有序集合的元素个数/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<long> SortedSetLengthAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.SortedSetLengthAsync(redisKey);}/// <summary>/// 返回有序集合的元素个数/// </summary>/// <param name="redisKey"></param>/// <param name="memebr"></param>/// <returns></returns>public async Task<bool> SortedSetRemoveAsync(string redisKey, string memebr){redisKey = AddKeyPrefix(redisKey);return await _db.SortedSetRemoveAsync(redisKey, memebr);}/// <summary>/// SortedSet 新增/// </summary>/// <param name="redisKey"></param>/// <param name="member"></param>/// <param name="score"></param>/// <returns></returns>public async Task<bool> SortedSetAddAsync<T>(string redisKey, T member, double score){redisKey = AddKeyPrefix(redisKey);var json = Serialize(member);return await _db.SortedSetAddAsync(redisKey, json, score);}#endregion SortedSet-Async#endregion SortedSet 操作#region key 操作/// <summary>/// 移除指定 Key/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public bool KeyDelete(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.KeyDelete(redisKey);}/// <summary>/// 移除指定 Key/// </summary>/// <param name="redisKeys"></param>/// <returns></returns>public long KeyDelete(IEnumerable<string> redisKeys){var keys = redisKeys.Select(x => (RedisKey)AddKeyPrefix(x));return _db.KeyDelete(keys.ToArray());}/// <summary>/// 校验 Key 是否存在/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public bool KeyExists(string redisKey){redisKey = AddKeyPrefix(redisKey);return _db.KeyExists(redisKey);}/// <summary>/// 重命名 Key/// </summary>/// <param name="redisKey"></param>/// <param name="redisNewKey"></param>/// <returns></returns>public bool KeyRename(string redisKey, string redisNewKey){redisKey = AddKeyPrefix(redisKey);return _db.KeyRename(redisKey, redisNewKey);}/// <summary>/// 设置 Key 的时间/// </summary>/// <param name="redisKey"></param>/// <param name="expiry"></param>/// <returns></returns>public bool KeyExpire(string redisKey, TimeSpan? expiry){redisKey = AddKeyPrefix(redisKey);return _db.KeyExpire(redisKey, expiry);}#region key-async/// <summary>/// 移除指定 Key/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<bool> KeyDeleteAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.KeyDeleteAsync(redisKey);}/// <summary>/// 移除指定 Key/// </summary>/// <param name="redisKeys"></param>/// <returns></returns>public async Task<long> KeyDeleteAsync(IEnumerable<string> redisKeys){var keys = redisKeys.Select(x => (RedisKey)AddKeyPrefix(x));return await _db.KeyDeleteAsync(keys.ToArray());}/// <summary>/// 校验 Key 是否存在/// </summary>/// <param name="redisKey"></param>/// <returns></returns>public async Task<bool> KeyExistsAsync(string redisKey){redisKey = AddKeyPrefix(redisKey);return await _db.KeyExistsAsync(redisKey);}/// <summary>/// 重命名 Key/// </summary>/// <param name="redisKey"></param>/// <param name="redisNewKey"></param>/// <returns></returns>public async Task<bool> KeyRenameAsync(string redisKey, string redisNewKey){redisKey = AddKeyPrefix(redisKey);return await _db.KeyRenameAsync(redisKey, redisNewKey);}/// <summary>/// 设置 Key 的时间/// </summary>/// <param name="redisKey"></param>/// <param name="expiry"></param>/// <returns></returns>public async Task<bool> KeyExpireAsync(string redisKey, TimeSpan? expiry){redisKey = AddKeyPrefix(redisKey);return await _db.KeyExpireAsync(redisKey, expiry);}#endregion key-async#endregion key 操作#region 发布订阅/// <summary>/// 订阅/// </summary>/// <param name="channel"></param>/// <param name="handle"></param>public void Subscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handle){var sub = _connMultiplexer.GetSubscriber();sub.Subscribe(channel, handle);}/// <summary>/// 发布/// </summary>/// <param name="channel"></param>/// <param name="message"></param>/// <returns></returns>public long Publish(RedisChannel channel, RedisValue message){var sub = _connMultiplexer.GetSubscriber();return sub.Publish(channel, message);}/// <summary>/// 发布(使用序列化)/// </summary>/// <typeparam name="T"></typeparam>/// <param name="channel"></param>/// <param name="message"></param>/// <returns></returns>public long Publish<T>(RedisChannel channel, T message){var sub = _connMultiplexer.GetSubscriber();return sub.Publish(channel, Serialize(message));}#region 发布订阅-async/// <summary>/// 订阅/// </summary>/// <param name="channel"></param>/// <param name="handle"></param>public async Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handle){var sub = _connMultiplexer.GetSubscriber();await sub.SubscribeAsync(channel, handle);}/// <summary>/// 发布/// </summary>/// <param name="channel"></param>/// <param name="message"></param>/// <returns></returns>public async Task<long> PublishAsync(RedisChannel channel, RedisValue message){var sub = _connMultiplexer.GetSubscriber();return await sub.PublishAsync(channel, message);}/// <summary>/// 发布(使用序列化)/// </summary>/// <typeparam name="T"></typeparam>/// <param name="channel"></param>/// <param name="message"></param>/// <returns></returns>public async Task<long> PublishAsync<T>(RedisChannel channel, T message){var sub = _connMultiplexer.GetSubscriber();return await sub.PublishAsync(channel, Serialize(message));}#endregion 发布订阅-async#endregion 发布订阅#region private method/// <summary>/// 添加 Key 的前缀/// </summary>/// <param name="key"></param>/// <returns></returns>private string AddKeyPrefix(string key){return $"{DefaultKey}:{key}";}#region 注册事件/// <summary>/// 添加注册事件/// </summary>private 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;}/// <summary>/// 重新配置广播时(通常意味着主从同步更改)/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void ConnMultiplexer_ConfigurationChangedBroadcast(object sender, EndPointEventArgs e){Console.WriteLine($"{nameof(ConnMultiplexer_ConfigurationChangedBroadcast)}: {e.EndPoint}");}/// <summary>/// 发生内部错误时(主要用于调试)/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void ConnMultiplexer_InternalError(object sender, InternalErrorEventArgs e){Console.WriteLine($"{nameof(ConnMultiplexer_InternalError)}: {e.Exception}");}/// <summary>/// 更改集群时/// </summary>/// <param name="sender"></param>/// <param name="e"></param>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}, ");}/// <summary>/// 配置更改时/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void ConnMultiplexer_ConfigurationChanged(object sender, EndPointEventArgs e){Console.WriteLine($"{nameof(ConnMultiplexer_ConfigurationChanged)}: {e.EndPoint}");}/// <summary>/// 发生错误时/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void ConnMultiplexer_ErrorMessage(object sender, RedisErrorEventArgs e){Console.WriteLine($"{nameof(ConnMultiplexer_ErrorMessage)}: {e.Message}");}/// <summary>/// 物理连接失败时/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void ConnMultiplexer_ConnectionFailed(object sender, ConnectionFailedEventArgs e){Console.WriteLine($"{nameof(ConnMultiplexer_ConnectionFailed)}: {e.Exception}");}/// <summary>/// 建立物理连接时/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void ConnMultiplexer_ConnectionRestored(object sender, ConnectionFailedEventArgs e){Console.WriteLine($"{nameof(ConnMultiplexer_ConnectionRestored)}: {e.Exception}");}#endregion 注册事件/// <summary>/// 序列化/// </summary>/// <param name="obj"></param>/// <returns></returns>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;}}/// <summary>/// 反序列化/// </summary>/// <typeparam name="T"></typeparam>/// <param name="data"></param>/// <returns></returns>private static T Deserialize<T>(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;}}#endregion private method}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/205205.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

探索Scrapy-spider:构建高效网络爬虫

Spider简介 Scrapy中的Spider是用于定义和执行数据抓取逻辑的核心组件。Spider负责从指定的网站抓取数据&#xff0c;并定义了如何跟踪链接、解析内容以及提取数据的规则。它允许您定制化地指定要抓取的网站、页面和所需的信息。Spider的作用是按照预定的规则爬取网页&#xf…

【Rust】第一节:安装

1 说明 一些学习记录 环境&#xff1a;MacOS 2 步骤 1、执行curl --proto https --tlsv1.2 https://sh.rustup.rs -sSf | sh 2、看到打印 info: downloading installerWelcome to Rust!... ...This path will then be added to your PATH environment variable by modifyin…

边缘计算与人工智能的融合

随着物联网技术的迅猛发展&#xff0c;大量设备和传感器开始连接至互联网&#xff0c;产生了海量的数据。传统的云计算模式往往无法满足对数据实时性和隐私保护的需求&#xff0c;而边缘计算技术的兴起为解决这一难题提供了新的思路。边缘计算将数据处理和分析的功能下沉至数据…

Python作业答疑_6.22~6.25

一、Python 一班 1. 基数分割列表 1.1 问题描述 给定一无序数列&#xff0c;把数列的第一个数字当成基数&#xff0c;让数列中基数小的数字排在数列前面&#xff0c;比基数大的数字排在数列的后面。 1.2 问题示例 如数列&#xff1a;num[4,1,8,3,9,2,10,7]。基数为 4&…

产品成本收集器流程演示

感谢大佬的文章&#xff0c;我只是一个翻译搬运工&#xff0c;原文地址&#xff1a;产品成本收集器 概述 SAP 令人兴奋的部分之一是它在不同操作模块之间的集成程度。使用产品成本收集器来跟踪生产就是一个很好的例子。在本博客中&#xff0c;我计划遵循产品成本收集器流程&a…

JAVA刷题之数组的总结和思路分享

꒰˃͈꒵˂͈꒱ write in front ꒰˃͈꒵˂͈꒱ ʕ̯•͡˔•̯᷅ʔ大家好&#xff0c;我是xiaoxie.希望你看完之后,有不足之处请多多谅解&#xff0c;让我们一起共同进步૮₍❀ᴗ͈ . ᴗ͈ აxiaoxieʕ̯•͡˔•̯᷅ʔ—CSDN博客 本文由xiaoxieʕ̯•͡˔•̯᷅ʔ 原创 CSDN …

C语言第十六集(前)

1.关于那个整形存储入char的 是先取好补码,再截断 例: 2.%u是以十进制的形式打印无符号整数 3.注意(背):存储的char类型变量的补码为10000000的直接解析为-128 4.signed char 类型的变量取值范围是-128~127 5.unsigned char 类型的变量取值范围是0~255 6.有符号类型的变量…

2023.12.6 关于 Spring Boot 事务的基本概念

目录 事务基本概念 前置准备 Spring Boot 事务使用 编程式事务 声明式事务 Transactional 注解参数说明 Transational 对异常的处理 解决方案一 解决方案二 Transactional 的工作原理 面试题 Spring Boot 事务失效的场景有那些&#xff1f; 事务基本概念 事务指一…

如何解决5G基站高能耗问题?

安科瑞 须静燕 截至2023年10月&#xff0c;我国5G基站总数达321.5万个&#xff0c;占全国通信基站总数的28.1%。然而&#xff0c;随着5G基站数量的快速增长&#xff0c;基站的能耗问题也逐渐日益凸显&#xff0c;基站的用电给运营商带来了巨大的电费开支压力&#xff0c;降低5…

vue项目配置多个代理

在本地.env文件配置本地/测试/预发/正式 路径&#xff1a; 在vue.config.js 里面配置&#xff1a; module.exports defineConfig({transpileDependencies: false,lintOnSave: false,outputDir: process.env.VUE_APP_DIST,publicPath: /,css: {loaderOptions: {postcss: {// p…

Motion Plan之轨迹生成代码实现 (1)

Motion Plan之搜索算法笔记Motion Plan之基于采样的路径规划算法笔记Motion Plan之带动力学约束路径搜索 Motion Plan之轨迹生成笔记文章开始前先回顾下上次的带约束的轨迹生成&#xff0c;轨迹生成本质就是曲线拟合。曲线拟合常用的方法有&#xff1a;多项式、贝赛尔曲线、三…

“Notification.recipient“ must be a “User“ instance.

使用django的通知模块报错&#xff1a; Lib\site-packages\notifications\base\models.py class AbstractNotification(models.Model):recipient models.ForeignKey(settings.AUTH_USER_MODEL,on_deletemodels.CASCADE,related_namenotifications,verbose_name_(recipient),b…

第5节:Vue3 JavaScript 表达式

在 Vue3 中&#xff0c;JavaScript 表达式的使用方式与 Vue2 有所不同。 在 Vue3 中&#xff0c;你可以使用 v-bind 指令来绑定 JavaScript 表达式。例如&#xff1a; <template><div>{{ count }}</div> </template><script> import { ref } f…

CPU密集型和IO密集型与CPU内核之间的关系

CPU密集型和IO密集型与CPU内核之间的关系 一、CPU密集型 介绍 CPU密集型&#xff0c;也叫计算密集型&#xff0c;是指需要大量CPU计算资源&#xff0c;例如大量的数学运算、图像处理、加密解密等。这种类型的任务主要依赖于CPU的计算能力&#xff0c;会占用大量的CPU时间片&am…

vcomp140.dll文件丢失解决方法分享:三种亲测有效方案

在计算机使用过程中&#xff0c;我们经常会遇到一些错误提示&#xff0c;其中之一就是“vcomp140.dll丢失”。这个错误提示通常出现在运行某些程序或游戏时&#xff0c;给使用者带来了很大的困扰。那么&#xff0c;vcomp140.dll丢失怎样修复呢&#xff1f;本文将详细介绍解决这…

Spark低版本适配Celeborn

Spark-3.5版本以下使用Celeborn时&#xff0c;无法使用动态资源&#xff0c;对于低版本的Spark&#xff0c;Celeborn提供了patch。各版本patch如下 https://github.com/apache/incubator-celeborn/tree/main/assets/spark-patch 下载patch&#xff0c;这里下载spark-3版本&am…

网工内推 | 国企网工、运维,厂商认证优先,13薪,带薪年假

01 中百集团 招聘岗位&#xff1a;运维工程师 职责描述&#xff1a; 1、对集团内使用云计算架构&#xff08;Kubernetes&#xff09;的系统进行规划、运维及管理相关工作。 2、对集团数据中心系统的大数据基础架构&#xff08;Cloudera Distribution Hadoop&#xff09;的规划…

打补丁,生成.diff文件

作者&#xff1a;爱塔居 文章目录 目录 前言 步骤 一、在根目录上&#xff0c;输入添加指令 二、输入修改内容指令 三、生成补丁 前言 自己的理解&#xff0c;仅供参考&#xff0c;欢迎指正。 补丁的话&#xff0c;在我看来就是方便评审&#xff0c;更方便看修改代码吧。 步骤…

Python-关系运算符详解

关系运算符&#xff1a;比较两个操作数的大小或者相等关系 < > ! 1、关系运算符的关系表达式返回值是布尔类型bool 成立就是真&#xff0c;即1&#xff1b;不成立就是假&#xff0c;即0 2、关系运算符还可以比较字符 字符根据字典序比较&#xff0c;先看首字母在…

Nginx(配置SLL证书)

随着越来越多的网站接入HTTPS&#xff0c;因此Nginx中仅配置HTTP还不够&#xff0c;往往还需要监听443端口的请求&#xff0c;HTTPS为了确保通信安全&#xff0c;所以服务端需配置对应的数字证书&#xff0c;当项目使用Nginx作为网关时&#xff0c;那么证书在Nginx中也需要配置…