C# Redis帮助类
这里只列举了string类型的操作,后续持续更新
using StackExchange.Redis; using System.Runtime.Serialization; using System.Xml; namespace WebApi.Services { /// <summary> /// Redis帮助类 /// </summary> public class RedisHelper { #region 私有参数 /// <summary> /// Key的前缀 /// </summary> private static string? _keyPrefix; /// <summary> /// 数据库连接字符串 /// </summary> private readonly string? _connectionString; /// <summary> /// 默认数据库 /// </summary> private readonly int _defaultDB; /// <summary> /// 数据库连接对象 /// </summary> private readonly IConnectionMultiplexer _connMultiplexer; /// <summary> /// 数据库对象 /// </summary> private readonly IDatabase _db; /// <summary> /// 操作数据库的锁 /// </summary> private readonly object _lock = new(); /// <summary> /// 数据库对象 /// </summary> public IDatabase DB { get { return _db; } } #endregion #region 构造函数 /// <summary> /// 构造函数 /// </summary> /// <param name="configuration"></param> public RedisHelper(IConfiguration configuration) { lock (_lock) { // 数据库信息 _connectionString = configuration["Redis:ConnectionString"]; _defaultDB = Convert.ToInt32(configuration["Redis:DefaultDB"]); _keyPrefix = configuration["Redis:KeyPrefix"]; ArgumentNullException.ThrowIfNull(_connectionString, nameof(_connectionString)); ArgumentNullException.ThrowIfNull(_defaultDB, nameof(_defaultDB)); ArgumentNullException.ThrowIfNull(_keyPrefix, nameof(_keyPrefix)); // 数据库连接 _connMultiplexer = ConnectionMultiplexer.Connect(_connectionString); _db = _connMultiplexer.GetDatabase(_defaultDB); } } #endregion #region 递增、递减 /// <summary> /// 递增 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public long Increment(string key, long value = 1) { return _db.StringIncrement(AddKeyPrefix(key), value); } /// <summary> /// 递增 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public double Increment(string key, double value = 1) { return _db.StringIncrement(AddKeyPrefix(key), value); } /// <summary> /// 递减 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public long Decrement(string key, long value = 1) { return _db.StringDecrement(AddKeyPrefix(key), value); } /// <summary> /// 递减 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public double Decrement(string key, double value = 1) { return _db.StringDecrement(AddKeyPrefix(key), value); } /// <summary> /// 递增 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public async Task<long> IncrementAsync(string key, long value = 1) { return await _db.StringIncrementAsync(AddKeyPrefix(key), value); } /// <summary> /// 递增 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public async Task<double> IncrementAsync(string key, double value = 1) { return await _db.StringIncrementAsync(AddKeyPrefix(key), value); } /// <summary> /// 递减 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public async Task<long> DecrementAsync(string key, long value = 1) { return await _db.StringDecrementAsync(AddKeyPrefix(key), value); } /// <summary> /// 递减 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public async Task<double> DecrementAsync(string key, double value = 1) { return await _db.StringDecrementAsync(AddKeyPrefix(key), value); } #endregion #region String 操作 /// <summary> /// 保存字符串 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiry"></param> /// <returns></returns> public bool StringSet(string key, string value, TimeSpan? expiry = null) { return _db.StringSet(AddKeyPrefix(key), value, expiry); } /// <summary> /// 取得字符串 /// </summary> /// <param name="key"></param> /// <returns></returns> public string? StringGet(string key) { return _db.StringGet(AddKeyPrefix(key)); } /// <summary> /// 保存字符串(多个 Key-value) /// </summary> /// <param name="keyValuePairs"></param> /// <returns></returns> public bool StringSet(IEnumerable<KeyValuePair<string, string>> keyValuePairs) { var pairs = keyValuePairs.Select(x => new KeyValuePair<RedisKey, RedisValue>(AddKeyPrefix(x.Key), x.Value)); return _db.StringSet(pairs.ToArray()); } /// <summary> /// 取得字符串(多个 Key-value) /// </summary> /// <param name="keys"></param> /// <returns></returns> public IEnumerable<string>? StringGet(IEnumerable<string> keys) { var redisKeys = keys.Select(x => new RedisKey(AddKeyPrefix(x))); return _db.StringGet(redisKeys.ToArray()).Select(x => x.ToString()); } /// <summary> /// 保存一个对象(序列化) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiry"></param> /// <returns></returns> public bool StringSet<T>(string key, T value, TimeSpan? expiry = null) { var data = Serialize<T>(value); return _db.StringSet(AddKeyPrefix(key), data, expiry); } /// <summary> /// 取得一个对象(反序列化) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T? StringGet<T>(string key) { return Deserialize<T>(_db.StringGet(AddKeyPrefix(key))); } #endregion #region String 异步操作 /// <summary> /// 保存字符串 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiry"></param> /// <returns></returns> public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = null) { return await _db.StringSetAsync(AddKeyPrefix(key), value, expiry); } /// <summary> /// 取得字符串 /// </summary> /// <param name="key"></param> /// <returns></returns> public async Task<string?> StringGetAsync(string key) { return await _db.StringGetAsync(AddKeyPrefix(key)); } /// <summary> /// 保存字符串(多个 Key-value) /// </summary> /// <param name="keyValuePairs"></param> /// <returns></returns> public async Task<bool> StringSetAsync(IEnumerable<KeyValuePair<string, string>> keyValuePairs) { var pairs = keyValuePairs.Select(x => new KeyValuePair<RedisKey, RedisValue>(AddKeyPrefix(x.Key), x.Value)); return await _db.StringSetAsync(pairs.ToArray()); } /// <summary> /// 取得字符串(多个 Key-value) /// </summary> /// <param name="keys"></param> /// <returns></returns> public async Task<IEnumerable<string>?> StringGetAsync(IEnumerable<string> keys) { var redisKeys = keys.Select(x => new RedisKey(AddKeyPrefix(x))); var redisValues = await _db.StringGetAsync(redisKeys.ToArray()); return redisValues.Select(x => x.ToString()); } /// <summary> /// 保存一个对象(序列化) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiry"></param> /// <returns></returns> public async Task<bool> StringSetAsync<T>(string key, T value, TimeSpan? expiry = null) { var data = Serialize<T>(value); return await _db.StringSetAsync(AddKeyPrefix(key), data, expiry); } /// <summary> /// 取得一个对象(反序列化) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public async Task<T?> StringGetAsync<T>(string key) { var redisValue = await _db.StringGetAsync(AddKeyPrefix(key)); return Deserialize<T>(redisValue); } #endregion #region 私有函数 /// <summary> /// 添加 Key 的前缀 /// </summary> /// <param name="key"></param> /// <returns></returns> private static string AddKeyPrefix(string key) { return _keyPrefix + key; } /// <summary> /// 序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> private static byte[]? Serialize<T>(T? obj) { if (obj == null) return default; using var memoryStream = new MemoryStream(); DataContractSerializer ser = new(typeof(T)); ser.WriteObject(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; using var memoryStream = new MemoryStream(data); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new(typeof(T)); var result = (T?)ser.ReadObject(reader, true); return result; } #endregion } }