redis 通用类
2022/1/29 19:06:31
本文主要是介绍redis 通用类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public interface IRedisManage { /// <summary> /// 设置一个 键值对 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="ts"></param> void Set(string key, object value, TimeSpan ts); /// <summary> /// //获取 Reids 缓存值 /// </summary> /// <param name="key"></param> /// <returns></returns> string GetValue(string key); /// <summary> /// 获取序列化值 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="key"></param> /// <returns></returns> TEntity Get<TEntity>(string key); /// <summary> /// 判断Key是否存在 /// </summary> /// <param name="key"></param> /// <returns></returns> bool Get(string key); /// <summary> /// 移除某个Key和值 /// </summary> /// <param name="key"></param> void Remove(string key); /// <summary> /// 清空Redis /// </summary> void Clear(); /// <summary> /// 异步获取 Reids 缓存值 /// </summary> /// <param name="key"></param> /// <returns></returns> Task<string> GetValueAsync(string key); /// <summary> /// 异步获取序列化值 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="key"></param> /// <returns></returns> Task<TEntity> GetAsync<TEntity>(string key); Task SetAsync(string key, object value, TimeSpan cacheTime); Task<bool> GetAsync(string key); /// <summary> /// 异步移除指定的key /// </summary> /// <param name="key"></param> /// <returns></returns> Task RemoveAsync(string key); /// <summary> /// 异步移除模糊查询到的key /// </summary> /// <param name="key"></param> /// <returns></returns> Task RemoveByKey(string key); /// <summary> /// 异步全部清空 /// </summary> /// <returns></returns> Task ClearAsync(); }IRedisManage
public class RedisManage : IRedisManage { public volatile ConnectionMultiplexer _redisConnection; private readonly object _redisConnectionLock = new object(); private readonly ConfigurationOptions _configOptions; private readonly ILogger<RedisManage> _logger; public RedisManage(ILogger<RedisManage> logger) { _logger = logger; ConfigurationOptions options = ReadRedisSetting(); if (options == null) { _logger.LogError("Redis数据库配置有误"); } this._configOptions = options; this._redisConnection = ConnectionRedis(); } private ConfigurationOptions ReadRedisSetting() { try { List<RedisConfig> config = AppHelper.ReadAppSettings<RedisConfig>(new string[] { "Redis" }); // 读取Redis配置信息 if (config.Any()) { ConfigurationOptions options = new ConfigurationOptions { EndPoints = { { config.FirstOrDefault().Ip, config.FirstOrDefault().Port } }, ClientName = config.FirstOrDefault().Name, Password = config.FirstOrDefault().Password, ConnectTimeout = config.FirstOrDefault().Timeout, DefaultDatabase = config.FirstOrDefault().Db, }; return options; } return null; } catch (Exception ex) { _logger.LogError($"获取Redis配置信息失败:{ex.Message}"); return null; } } private ConnectionMultiplexer ConnectionRedis() { if (this._redisConnection != null && this._redisConnection.IsConnected) { return this._redisConnection; // 已有连接,直接使用 } lock (_redisConnectionLock) { if (this._redisConnection != null) { this._redisConnection.Dispose(); // 释放,重连 } try { this._redisConnection = ConnectionMultiplexer.Connect(_configOptions); } catch (Exception ex) { _logger.LogError($"Redis服务启动失败:{ex.Message}"); } } return this._redisConnection; } public string GetValue(string key) { return _redisConnection.GetDatabase().StringGet(key); } public void Set(string key, object value, TimeSpan ts) { if (value != null) { _redisConnection.GetDatabase().StringSet(key, JsonConvert.SerializeObject(value), ts); } } public void Clear() { foreach (var endPoint in this.ConnectionRedis().GetEndPoints()) { var server = this.ConnectionRedis().GetServer(endPoint); foreach (var key in server.Keys()) { _redisConnection.GetDatabase().KeyDelete(key); } } } public bool Get(string key) { return _redisConnection.GetDatabase().KeyExists(key); } public TEntity Get<TEntity>(string key) { var value = _redisConnection.GetDatabase().StringGet(key); if (value.HasValue) { //需要用的反序列化,将Redis存储的Byte[],进行反序列化 return JsonConvert.DeserializeObject<TEntity>(value); } else { return default(TEntity); } } public void Remove(string key) { _redisConnection.GetDatabase().KeyDelete(key); } public bool SetValue(string key, byte[] value) { return _redisConnection.GetDatabase().StringSet(key, value, TimeSpan.FromSeconds(120)); } public async Task ClearAsync() { foreach (var endPoint in this.ConnectionRedis().GetEndPoints()) { var server = this.ConnectionRedis().GetServer(endPoint); foreach (var key in server.Keys()) { await _redisConnection.GetDatabase().KeyDeleteAsync(key); } } } public async Task<bool> GetAsync(string key) { return await _redisConnection.GetDatabase().KeyExistsAsync(key); } public async Task<string> GetValueAsync(string key) { return await _redisConnection.GetDatabase().StringGetAsync(key); } public async Task<TEntity> GetAsync<TEntity>(string key) { var value = await _redisConnection.GetDatabase().StringGetAsync(key); if (value.HasValue) { return JsonConvert.DeserializeObject<TEntity>(value); } else { return default; } } public async Task RemoveAsync(string key) { await _redisConnection.GetDatabase().KeyDeleteAsync(key); } public async Task RemoveByKey(string key) { var redisResult = await _redisConnection.GetDatabase().ScriptEvaluateAsync(LuaScript.Prepare( //模糊查询: " local res = redis.call('KEYS', @keypattern) " + " return res "), new { @keypattern = key }); if (!redisResult.IsNull) { var keys = (string[])redisResult; foreach (var k in keys) _redisConnection.GetDatabase().KeyDelete(k); } } public async Task SetAsync(string key, object value, TimeSpan cacheTime) { if (value != null) { await _redisConnection.GetDatabase().StringSetAsync(key, JsonConvert.SerializeObject(value), cacheTime); } } public async Task<bool> SetValueAsync(string key, byte[] value) { return await _redisConnection.GetDatabase().StringSetAsync(key, value, TimeSpan.FromSeconds(120)); } }RedisManage
这篇关于redis 通用类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-08阿里云Redis项目实战入门教程
- 2024-11-08阿里云Redis资料:新手入门与初级使用指南
- 2024-11-08阿里云Redis教程:新手入门及实用指南
- 2024-11-07阿里云Redis学习入门:新手必读指南
- 2024-11-07阿里云Redis学习入门:从零开始的操作指南
- 2024-11-07阿里云Redis学习:初学者指南
- 2024-11-06阿里云Redis入门教程:轻松搭建与使用指南
- 2024-11-02Redis项目实战:新手入门教程
- 2024-10-22Redis入门教程:轻松掌握数据存储与操作
- 2024-10-22Redis缓存入门教程:快速掌握Redis缓存基础知识