.net RedisHelper

NuGet安装: StackExchange.Redis


Appsettings.json 设置:

{

"RedisIP": "192.168.1.123:4567",

"RedisDB": "0", //Redis数据库编号

}


cs 复制代码
using Newtonsoft.Json;
using StackExchange.Redis;
using System.Configuration;

namespace TempAndRhCtrl
{
    /// <summary>
    /// Redis帮助类
    /// config里添加设置:
    ///     //Redis连接字符串:
    ///     "RedisIP": "192.168.1.123:4567",
    ///     "RedisDB": "0", //Redis数据库编号
    /// </summary>
    public class RedisHelper
    {
        private static string Connstr;//readonly

        private static int Database = 0;//readonly
        private static ConnectionMultiplexer _redis;
        private static object Locker = new object();//readonly

        private static ConnectionMultiplexer Conn;
        private static IDatabase Db;

        public static string RedisIP = Tools.ToString(CustomConfigManager.GetConfig("RedisIP"), "");//Redis连接字符串
        public static string RedisDB = Tools.ToString(CustomConfigManager.GetConfig("RedisDB"), "0");//Redis数据库编号

        #region 初始化
        static RedisHelper()
        {
            try
            {
                Connstr = RedisIP;//例:192.168.1.123:4567 
                Database = Convert.ToInt32(RedisDB);//例:0
                Conn = ConnectionMultiplexer.Connect(Connstr);

                Db = Conn == null ? null : Conn.GetDatabase(Database);//Db = Conn == null ? null : Conn.GetDatabase(0);
            }
            catch (Exception ex)
            {
                throw new Exception($"Redis连接失败,IP:{Connstr},错误码 : {GetLineNum(ex)}");
            }
        }

        #endregion

        public static string GetAppsettingStr(string str)
        {
            AppSettingsReader appReader = new AppSettingsReader();
            return appReader.GetValue(str, typeof(string)).ToString();
        }

        public static ConnectionMultiplexer Manager
        {
            get
            {
                if (_redis == null)
                {
                    lock (Locker)
                    {
                        if (_redis != null) return _redis;

                        _redis = GetManager();
                        return _redis;
                    }
                }

                return _redis;
            }
        }


        private static ConnectionMultiplexer GetManager(string connectionString = null)
        {
            try
            {
                if (string.IsNullOrEmpty(connectionString))
                {
                    connectionString = Connstr;
                }

                var options = ConfigurationOptions.Parse(connectionString);
                options.ConnectTimeout = 20000;//连接操作超时(ms)
                options.KeepAlive = 180;//发送消息以帮助保持套接字活动的时间(秒)(默认为60秒)
                options.SyncTimeout = 2000;//时间(ms)允许进行同步操作
                options.ConnectRetry = 3;//重试连接的次数

                return ConnectionMultiplexer.Connect(options);
            }
            catch (Exception)
            {
                return null;
            }
        }

        #region String 可以设置过期时间

        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="key">Redis Key</param>
        /// <param name="value">保存的值</param>
        /// <param name="expiry">过期时间</param>
        /// <returns></returns>
        public static bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
        {
            try
            {
                var db = Manager.GetDatabase(Database);
                return db.StringSet(key, value, expiry);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 保存多个key value
        /// </summary>
        /// <param name="arr">key</param>
        /// <returns></returns>
        public static bool SetStringKey(KeyValuePair<RedisKey, RedisValue>[] arr)
        {
            try
            {
                var db = Manager.GetDatabase(Database);
                return db.StringSet(arr);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 保存一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="expiry"></param>
        /// <returns></returns>
        public static bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
        {
            try
            {
                string json = JsonConvert.SerializeObject(obj);
                var db = Manager.GetDatabase(Database);
                return db.StringSet(key, json, expiry);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取单个key的值
        /// </summary>
        /// <param name="key">Redis Key</param>
        /// <returns></returns>

        public static RedisValue GetStringKey(string key)
        {
            var db = Manager.GetDatabase(Database);
            return db.StringGet(key);
        }

        /// <summary>
        /// 获取多个Key
        /// </summary>
        /// <param name="listKey">Redis Key集合</param>
        /// <returns></returns>
        public static RedisValue[] GetStringKey(List<RedisKey> listKey)
        {
            var db = Manager.GetDatabase(Database);
            return db.StringGet(listKey.ToArray());
        }

        /// <summary>
        /// 获取一个key的对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetObjectKey(string key)
        {
            try
            {
                var db = Manager.GetDatabase(Database);
                return db.StringGet(key).ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        /// 获取一个key的对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetObjectKey<T>(string key)
        {
            try
            {
                var db = Manager.GetDatabase(Database);

                if ((db.StringGet(key) == RedisValue.Null))
                {
                    return "";
                }
                else
                {
                    var redisKey = db.StringGet(key);
                    return JsonConvert.DeserializeObject<T>(redisKey.ToString()).ToString();
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        #endregion

        #region Hash

        /// <summary>
        /// 保存一个集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Redis Key</param>
        /// <param name="list">数据集合</param>
        /// <param name="getModelId"></param>
        public static void HashSet<T>(string key, List<T> list, Func<T, string> getModelId)
        {
            List<HashEntry> listHashEntry = new List<HashEntry>();
            foreach (var item in list)
            {
                string json = JsonConvert.SerializeObject(item);
                listHashEntry.Add(new HashEntry(getModelId(item), json));
            }

            var db = Manager.GetDatabase(Database);
            db.HashSet(key, listHashEntry.ToArray());
        }

        /// <summary>
        /// 获取Hash中的单个key的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Redis Key</param>
        /// <param name="hasFildValue">RedisValue</param>
        /// <returns></returns>
        public static T GetHashKey<T>(string key, string hasFildValue)
        {
            if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(hasFildValue))
            {
                var db = Manager.GetDatabase(Database);
                RedisValue value = db.HashGet(key, hasFildValue);
                if (!value.IsNullOrEmpty)
                {
                    return JsonConvert.DeserializeObject<T>(value);
                }
            }
            return default(T);
        }

        /// <summary>
        /// 获取hash中的多个key的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Redis Key</param>
        /// <param name="listhashFields">RedisValue value</param>
        /// <returns></returns>
        public static List<T> GetHashKey<T>(string key, List<RedisValue> listhashFields)
        {
            List<T> result = new List<T>();
            if (!string.IsNullOrWhiteSpace(key) && listhashFields.Count > 0)
            {
                var db = Manager.GetDatabase(Database);

                RedisValue[] value = db.HashGet(key, listhashFields.ToArray());
                foreach (var item in value)
                {
                    if (!item.IsNullOrEmpty)
                    {
                        result.Add(JsonConvert.DeserializeObject<T>(item));
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取hashkey所有Redis key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List<T> GetHashAll<T>(string key)
        {
            var db = Manager.GetDatabase(Database);

            List<T> result = new List<T>();
            RedisValue[] arr = db.HashKeys(key);
            foreach (var item in arr)
            {
                if (!item.IsNullOrEmpty)
                {
                    result.Add(JsonConvert.DeserializeObject<T>(item));
                }
            }
            return result;
        }

        /// <summary>
        /// 获取hashkey所有的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List<T> HashGetAll<T>(string key)
        {
            var db = Manager.GetDatabase(Database);

            List<T> result = new List<T>();
            HashEntry[] arr = db.HashGetAll(key);
            foreach (var item in arr)
            {
                if (!item.Value.IsNullOrEmpty)
                {
                    result.Add(JsonConvert.DeserializeObject<T>(item.Value));
                }
            }
            return result;
        }

        /// <summary>
        /// 删除hasekey
        /// </summary>
        /// <param name="key"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public static bool DeleteHase(RedisKey key, RedisValue hashField)
        {
            var db = Manager.GetDatabase(Database);
            return db.HashDelete(key, hashField);
        }

        #endregion

        #region key

        /// <summary>
        /// 删除单个key
        /// </summary>
        /// <param name="key">redis key</param>
        /// <returns>是否删除成功</returns>
        public static bool KeyDelete(string key)
        {
            var db = Manager.GetDatabase(Database);
            return db.KeyDelete(key);
        }

        /// <summary>
        /// 删除多个key
        /// </summary>
        /// <param name="keys">rediskey</param>
        /// <returns>成功删除的个数</returns>
        public static long KeyDelete(RedisKey[] keys)
        {
            var db = Manager.GetDatabase(Database);
            return db.KeyDelete(keys);
        }

        /// <summary>
        /// 判断key是否存储
        /// </summary>
        /// <param name="key">redis key</param>
        /// <returns></returns>
        public static bool KeyExists(string key)
        {
            var db = Manager.GetDatabase(Database);
            return db.KeyExists(key);
        }

        /// <summary>
        /// 重新命名key
        /// </summary>
        /// <param name="key">就的redis key</param>
        /// <param name="newKey">新的redis key</param>
        /// <returns></returns>
        public static bool KeyRename(string key, string newKey)
        {
            var db = Manager.GetDatabase(Database);
            return db.KeyRename(key, newKey);
        }
        #endregion

        #region Search Keys
        public static List<string> SearchKeys(string key)
        {
            List<string> list = null;
            for (int i = 1; i <= 5; i++)
            {
                bool bFlag = KeyExists(key + "_" + i);
                string value = RedisHelper.GetObjectKey(key + "_" + i);

                if (!string.IsNullOrEmpty(value))
                {
                    if (list == null)
                        list = new List<string>();

                    list.Add(value);
                }
            }
            return list;

        }
        #endregion


        #region List操作
        /// <summary>
        /// 删除指定List<T>中满足条件的元素
        /// </summary>
        /// <param name="listkey">Key</param>
        /// <param name="func">lamdba表达式</param>
        /// <param name="db_index">数据库序号,不传默认为0</param>
        /// <returns></returns>
        public static bool delListByLambda<T>(string listkey, Func<T, bool> func, int db_index = 0)
        {
            var db = Manager.GetDatabase(db_index);
            if (db.KeyExists(listkey))
            {
                var value = db.StringGet(listkey);
                if (!string.IsNullOrEmpty(value))
                {
                    var list = JsonConvert.DeserializeObject<List<T>>(value);
                    if (list.Count > 0)
                    {
                        list = list.SkipWhile<T>(func).ToList();
                        value = JsonConvert.SerializeObject(list);
                        return db.StringSet(listkey, value);
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 获取指定List<T>中满足条件的元素
        /// </summary>
        /// <param name="listkey">Key</param>
        /// <param name="func">lamdba表达式</param>
        /// <param name="db_index">数据库序号,不传默认为0</param>
        /// <returns></returns>
        public static List<T> getListByLambda<T>(string listkey, Func<T, bool> func, int db_index = 0)
        {
            var db = Manager.GetDatabase(db_index);
            if (db.KeyExists(listkey))
            {
                var value = db.StringGet(listkey);
                if (!string.IsNullOrEmpty(value))
                {
                    var list = JsonConvert.DeserializeObject<List<T>>(value);
                    if (list.Count > 0)
                    {
                        list = list.Where(func).ToList();
                        return list;
                    }
                    else
                    {
                        return new List<T>();
                    }
                }
                else
                {
                    return new List<T>();
                }
            }
            else
            {
                return new List<T>();
            }
        }
        #endregion


        #region 行数异常
        /// <summary>
        /// 获取出现异常的行数
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static int GetLineNum(Exception ex)
        {
            var str = ex.StackTrace.Substring(ex.StackTrace.IndexOf("line"), ex.StackTrace.Length - ex.StackTrace.IndexOf("line"));
            string result = System.Text.RegularExpressions.Regex.Replace(str, @"[^0-9]+", "");
            return Convert.ToInt32(result);
        }
        #endregion 
    }
}

调用:

var OverLimitList =RedisHelper.GetObjectKey("OverLimitList");//获取Redis字符串

bool b = RedisHelper.SetStringKey("OverLimitList", OverLimitList);//更新Redis

相关推荐
慧都小妮子30 分钟前
Spire.PDF for .NET【页面设置】演示:打开 PDF 时自动显示书签或缩略图
java·pdf·.net
霍先生的虚拟宇宙网络3 小时前
.net 支持跨平台(桌面)系列技术汇总
.net
djk88883 小时前
.net的winfrom程序 窗体透明&打开窗体时出现在屏幕右上角
.net
九鼎科技-Leo12 小时前
什么是 WPF 中的依赖属性?有什么作用?
windows·c#·.net·wpf
dot.Net安全矩阵17 小时前
.NET 通过模块和驱动收集本地EDR的工具
windows·安全·web安全·.net·交互
zls36536517 小时前
.NET开源实时应用监控系统:WatchDog
.net
djk888817 小时前
.net将List<实体1>的数据转到List<实体2>
数据结构·list·.net
Crazy Struggle1 天前
功能齐全的 WPF 自定义控件资源库(收藏版)
.net·wpf·ui控件库
时光追逐者1 天前
.NET 9 中 LINQ 新增功能实操
开发语言·开源·c#·.net·.netcore·linq·微软技术
zls3653651 天前
.NET高效下载word文件
开发语言·c#·word·.net