C# Redis应用

2021-02-15 15:24

阅读:621

标签:int   主键   eth   var   reac   消息   nta   mha   util   

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using TalentCloud.Common;
using TalentCloud.Base.Utils;

namespace TalentCloud.Base.RedisHelper
{
    /// 
    /// 配置管理和初始化
    /// 
    internal class Managers
    {
        /// 
        /// 最大读写数量
        /// 
        const int writeReadCount = 100000;

        //private static string hostString = TCConfigManager.GetConfig("RedisHost").ToString();
        private static string hostString = ConfigurationManager.AppSettings["RedisHost"].TryString();

        private static string[] writeHosts = hostString.Split(‘,‘);
        private static string[] readHosts = hostString.Split(‘,‘);

        private static int poolConnectTimeout = 1000 * 60 * 2;

        //private static string[] writeHosts = "".Split(‘,‘);
        //private static string[] readHosts = "".Split(‘,‘);

        //Singleton保证只有一个对象
        private static Managers PoolManagers =  null;


        private static  Dictionary ClientManagerList=new Dictionary();

        private static PooledRedisClientManager ClientManagers { get; set; }

        internal PooledRedisClientManager GetClientManagers()
        {
            return ClientManagers;
        }

        public static Managers Instance()
        {
            if (PoolManagers == null)
            {
                PoolManagers = new Managers();
            }

            return PoolManagers;
        }

        //Singleton
        private Managers()
        {
            //Init();
        }

        public void Init()
        {
            //初始化时就创建好0~8的数据库连接
            for (int i = 0; i 

  

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Linq.Expressions;
using TalentCloud.Base.Utils;
using TalentCloud.Common;

namespace TalentCloud.Base.RedisHelper
{
    /// 
    /// redis客户端调用类
    /// 
    public class RedisClient
    {
        #region
        //初始化链接
        public static void InitRedisPool()
        {
            Managers.Instance().Init();
        }
        #endregion

        #region 写对象

        private string GetEntryId()
        {
            return typeof(T).FullName;
        }

        #region string 类型存储及操作

        /// 
        /// 写数据 永久保存
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool SetKeyValue(string key, T value,int db)
        {
            Func fun = (IRedisClient client) =>
            {
                client.SetEntry(key, value.ToJsonSerialize());
                // client.Save();//持久化到硬盘
                return true;
            };

            return TryRedisWrite(fun, db);
        }


        /// 
        /// 写数据 永久保存
        /// 
        /// 
        /// 
        /// 
        /// 
        public List GetListKeyValue(string key, int db)
        {
            Func> fun = (IRedisClient client) =>
            {
                return client.Get>(key);
            };

            return TryRedisRead(fun, db);
        }


        /// 
        /// 写数据 永久保存
        /// 
        /// 
        /// 
        /// 
        /// 
        public T GetKeyValue(string key, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.Get(key);
            };

            return TryRedisRead(fun, db);
        }

        /// 
        /// 写数据 需要传过期时间
        /// 
        /// 
        /// 
        /// TimeSpan.FromMinutes(30)
        /// 
        public bool SetKeyValue(string key, T value, int db, TimeSpan expireIn)
        {
            Func fun = (IRedisClient client) =>
            {
                client.Db = db;
                client.SetEntry(key, value.ToJsonSerialize(), expireIn);
                return true;
            };

            return TryRedisWrite(fun, db);
        }

        /// 
        /// 写数据 需要传过期时间 (只能写string类型数据)
        /// 
        /// 
        /// 
        /// 
        /// 
        public void SetKeyValue_String(string key, string value, TimeSpan expireIn, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                if (expireIn == System.TimeSpan.MinValue)
                {
                    client.SetEntry(key, value, TimeSpan.FromMinutes(30));//默认30分钟
                }
                else
                {
                    client.SetEntry(key, value, expireIn);
                }
                return false;
            };

            TryRedisWrite(fun, db);
        }

        /// 
        /// 以Key/Value的形式存储对象到缓存中
        /// 
        /// 对象类别
        /// 要写入的集合
        public void KSet(Dictionary value,int db)
        {
            Func fun = (IRedisClient client) =>
            {
                client.SetAll(value);
                return true;
            };

            TryRedisWrite(fun, db);
        }
        #endregion


        

        #region LIST 方式存储及操作
        /// 
        /// 获取key包含的所有数据集合T 分页获取 
        /// 
        /// 
        /// 
        /// 开始位置
        /// 大小
        /// 
        public List GetPageListT(string key, int pageIndex, int pageSize,int db)
        {
            int start = pageSize * (pageIndex - 1);
            return List_GetRange(key, start, pageSize, db);

        }

        private List List_GetRange(string key, int start, int count, int db)
        {
            Func> fun = (IRedisClient client) =>
            {
                // client.GetRangeFromSortedSet("")
                var c = client.GetTypedClient();
                return c.Lists[key].GetRange(start, start + count - 1);
            };

            return TryRedisRead(fun, db);
        }

        /// 
        /// 获取key包含的所有数据集合T
        /// 
        /// 
        /// 
        /// 
        public List Get(string key, Expression> expression, int db)
        {
            Func> fun = (IRedisClient client) =>
            {

                var c = client.GetTypedClient();
                if (expression != null)
                {
                    return c.Lists[key].GetAll().AsQueryable().Where(expression).ToList();
                }
                else
                {
                    return c.Lists[key].GetAll();
                }

            };

            return TryRedisRead(fun, db);
        }

        /// 
        /// 通过多个key包含的所有数据集合T
        /// 
        /// 
        /// 
        /// 
        public List Get(List keys, Expression> expression, int db)
        {
            List list = new List();
            foreach(string item in keys)
            {
                Func> fun = (IRedisClient client) =>
                {
                    var c = client.GetTypedClient(); 
                    if (expression != null)
                    {
                        return c.Lists[item].GetAll().AsQueryable().Where(expression).ToList();
                    }
                    else
                    {
                        return c.Lists[item].GetAll();
                    }
                };
                list.AddRange(TryRedisRead(fun, db));
            }

            return list;
            
        }

        /// 
        /// 获取key包含的所有数据集合T
        /// 
        /// 
        /// 
        /// 
        public List GetListT(string key,int db)
        {
            Func> fun = (IRedisClient client) =>
            {

                var c = client.GetTypedClient();
                return c.Lists[key].GetAll();
            };

            return TryRedisRead(fun,db);
        }

        /// 
        /// 从左侧向list中添加值 T
        /// 
        /// 
        /// 
        /// 
        public void LPushInList(string key, T t, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                redisTypedClient.PushItemToList(redisTypedClient.Lists[key], t);
                return true;
            };
            TryRedisRead(fun, db);
        }

        /// 
        /// 入队
        /// 
        /// 
        /// 
        /// 
        public bool EnqueueItemOnList(string key, T t)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                redisTypedClient.EnqueueItemOnList(redisTypedClient.Lists[key], t);
                return true;
            };
            return TryRedisWrite(fun,0);
        }

        /// 
        /// 出对
        /// 
        /// 
        /// 
        /// 
        public T DequeueItemFromList(string key)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                return redisTypedClient.DequeueItemFromList(redisTypedClient.Lists[key]);

            };
            return TryRedisRead(fun,0);
        }

        /// 
        /// 获取队列总数
        /// 
        /// 
        /// 
        /// 
        public int GetListCount(string key,int db)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                return redisTypedClient.GetListCount(redisTypedClient.Lists[key]);
            };
            return TryRedisRead(fun, db);
        }


        /// 
        /// 通过key移除list中某一个集合
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool List_Remove(string key, T t, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0;
            };

            return TryRedisRead(fun, db);

        }

        /// 
        /// 通过key 移除list集合
        /// 
        /// 
        /// 
        /// 
        public bool List_RemoveAll(string key, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                redisTypedClient.Lists[key].RemoveAll();
                return true;
            };

            return TryRedisRead(fun,db);
        }

        /// 
        /// key中是否包含 t
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool Set_Contains(string key, T t)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                return redisTypedClient.Sets[key].Contains(t);
            };
            return TryRedisRead(fun,0);

        }

        /// 
        /// 通过key移除list
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool Set_Remove(string key, T t,int db)
        {
            Func fun = (IRedisClient client) =>
            {
                var redisTypedClient = client.GetTypedClient();
                return redisTypedClient.Sets[key].Remove(t);
            };
            return TryRedisRead(fun,db);

        }

        #endregion list

        #region SortedSet 方式存储及操作
        /// 
        ///  添加数据到 SortedSet
        /// 
        /// 
        /// key
        /// values
        /// 排序
        public bool SortedSet_Add(string key, T t, double score)
        {
            Func fun = (IRedisClient client) =>
            {
                string value = t.ToJsonSerialize();
                return client.AddItemToSortedSet(key, value, score);
            };
            return TryRedisWrite(fun,0);

        }
        /// 
        /// 移除数据从SortedSet
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool SortedSet_Remove(string key, T t)
        {
            Func fun = (IRedisClient client) =>
            {
                string value = t.ToJsonSerialize();
                return client.RemoveItemFromSortedSet(key, value);
            };
            return TryRedisWrite(fun,0);
        }
        /// 
        /// 修剪SortedSet
        /// 
        /// 
        /// 保留的条数
        /// 
        public int SortedSet_Trim(string key, int size)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.RemoveRangeFromSortedSet(key, size, 9999999);
            };
            return TryRedisWrite(fun,0);


        }
        /// 
        /// 获取SortedSet的长度
        /// 
        /// 
        /// 
        public int SortedSet_Count(string key)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.GetSortedSetCount(key);
            };
            return TryRedisWrite(fun,0);

        }

        /// 
        /// 获取SortedSet的分页数据
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public List SortedSet_GetList(string key, int pageIndex, int pageSize)
        {
            Func> fun = (IRedisClient client) =>
            {
                var list = client.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1);
                if (list != null && list.Count > 0)
                {
                    List result = new List();
                    foreach (var item in list)
                    {
                        var data = item.DeserializeFromJson(false);
                        result.Add(data);
                    }
                    return result;
                }
                return null;
            };
            return TryRedisRead(fun,0);

        }


        /// 
        /// 获取SortedSet的全部数据
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public List SortedSet_GetListALL(string key)
        {
            Func> fun = (IRedisClient client) =>
            {
                var list = client.GetRangeFromSortedSet(key, 0, 9999999);
                if (list != null && list.Count > 0)
                {
                    List result = new List();
                    foreach (var item in list)
                    {
                        var data = item.DeserializeFromJson(false);
                        result.Add(data);
                    }
                    return result;
                }
                return null;
            };
            return TryRedisWrite(fun,0);

        }

        /// 
        /// 设置缓存过期
        /// 
        /// 
        /// 
        public bool SortedSet_SetExpire(string key, DateTime datetime)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.ExpireEntryAt(key, datetime);
            };
            return TryRedisWrite(fun,0);
        }

        #endregion



        /// 
        /// 通过key删除数据
        /// 
        /// 
        /// 
        /// 
        public bool KRemove(string key)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.Remove(key);
            };

            return TryRedisRead(fun,0);
        }

        #endregion 写对象

        #region 读对象

        /// 
        /// 根据ID获取指定对象 Hash类型数据
        /// 
        /// 需要获取的主键,一般为对象ID值
        /// 
        public T HGet(string key)
        {
            if (key == null)
            {
                return default(T);
            }

            Func fun = (IRedisClient client) =>
            {
                string ser = "";
                string hashId = GetEntryId();
                ser = client.GetValueFromHash(hashId, key.ToString());

                return ser == null ? default(T) : ser.DeserializeFromJson(false);
            };

            return TryRedisRead(fun,0);
        }


        //以hash方式存储
        public List GetHashKeys(string hashKey)
        {
            Func> fun = (IRedisClient client) =>
            {
                return client.GetHashKeys(hashKey);
            };
            return TryRedisRead(fun,0);
        }


        /// 
        /// 判断key是否存在
        /// 
        /// 
        /// 
        /// 
        public bool KIsExist(string key)
        {
            Func fun = (IRedisClient client) =>
            {
                string ser = "";
                ser = client.GetValue(key.ToString());

                return string.IsNullOrEmpty(ser) == false;
            };

            return TryRedisRead(fun,0);
        }


        /// 
        /// 读取Key/Value值
        /// 
        /// 
        /// 
        /// 
        public T KGet(string key)
        {
            Func fun = (IRedisClient client) =>
            {
                string ser = "";
                ser = client.GetValue(key);
                if (string.IsNullOrEmpty(ser) == false)
                {
                    return ser.DeserializeFromJson(false);
                }
                else
                {
                    return default(T);
                }
            };
            return TryRedisRead(fun,0);
        }

        public string GetStr(string key)
        {
            Func fun = (IRedisClient client) =>
            {
                string ser = "";
                ser = client.GetValue(key);
                if (string.IsNullOrEmpty(ser) == false)
                {
                    return ser;
                }
                else
                {
                    return default(string);
                }
            };
            return TryRedisRead(fun,0);
        }

        /// 
        /// 读取Key/Value值
        /// 
        /// 
        /// 
        /// 
        public Dictionary KGet(IList keys)
        {
            Func> fun = (IRedisClient client) =>
             {
                 return (Dictionary)client.GetAll(keys);
             };

            return TryRedisRead(fun,0);
        }

        /// 
        /// 读取Key/Value值
        /// 
        /// 
        /// 
        /// 
        public IList KGetList(IList keys)
        {
            Dictionary dics = KGet(keys);
            return dics.Values.ToList();
        }

        /// 
        /// 返回根据条件查找到的KEY对象列表        
        /// 
        /// 
        /// 
        /// 
        public IList KSearchKeys(string pattern)
        {
            Func> fun = (IRedisClient client) =>
            {
                return client.SearchKeys(pattern);
            };

            return TryRedisRead(fun,0);
        }

        /// 
        /// 返回根据条件查找到的value对象列表        
        /// 
        /// 
        /// 
        /// 
        public IList KSearchValues(string pattern)
        {
            Func> fun = (IRedisClient client) =>
            {
                IList keys = new List();

                //先查找KEY
                keys = client.SearchKeys(pattern);

                if (keys != null && keys.Count > 0)
                {
                    //再直接根据key返回对象列表
                    Dictionary dics = (Dictionary)client.GetAll(keys);

                    return dics.Values.ToList();
                }
                else
                {
                    return new List();
                }

            };

            return TryRedisRead(fun,0);
        }

        #endregion 读对象

        #region List方式存储以及操作

        /// 
        ///  入队
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool EnqueueList(string listId, string values, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                client.EnqueueItemOnList(listId, values);
                return true;
            };

            return TryRedisWrite(fun, db);
        }

        ///
        ///  出队
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public string DequeueList(string listId, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.DequeueItemFromList(listId);
            };
            return TryRedisRead(fun, db);
        }


        ///
        ///  获取队列的数量
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public int GetListCount(string listId, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.GetListCount(listId);
            };
            return TryRedisRead(fun, db);
        }

        #endregion

        #region hash方式存储及操作

        /// 
        /// 以hash方式存储
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool SetHash(string hashKey, string key, string values, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                client.SetEntryInHash(hashKey, key, values);
                return true;
            };

            return TryRedisWrite(fun, db);
        }

        /// 
        /// 移除指定的记录
        /// 
        /// 需要移除的主键,一般为对象ID值
        /// 
        public bool RemoveEntryFromHash(string hashId, string key, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.RemoveEntryFromHash(hashId, key);
            };

            return TryRedisWrite(fun, db);
        }

        /// 
        /// 获取所有hashid数据集的key/value数据集合
        /// 
        public Dictionary GetAllEntriesFromHash(string hashid, int db)
        {
            Func> fun = (IRedisClient client) =>
            {
                return client.GetAllEntriesFromHash(hashid);
            };
            return TryRedisRead(fun, db);
        }


        /// 
        /// 获取hashid数据集中所有key的集合
        /// 
        /// 
        /// 
        /// 
        public List GetHashKeys(string hashid, int db)
        {
            Func> fun = (IRedisClient client) =>
            {
                return client.GetHashKeys(hashid);
            };
            return TryRedisRead(fun, db);
        }


        /// 
        /// 获取hashid数据集中的所有value集合
        /// 
        public List GetHashValues(string hashid, int db)
        {
            Func> fun = (IRedisClient client) =>
            {
                return client.GetHashValues(hashid);
            };
            return TryRedisRead(fun, db);
        }

        /// 
        /// 获取hashid数据集中,key的value数据
        /// 
        public string GetValueFromHash(string hashid, string key, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.GetValueFromHash(hashid, key);
            };
            return TryRedisRead(fun, db);
        }

        /// 
        /// 判断hashid数据集中是否存在key的数据
        /// 
        public bool HashContainsEntry(string hashid, string key, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.HashContainsEntry(hashid, key);
            };
            return TryRedisWrite(fun, db);
        }
        #endregion

        #region 推送消息  
        /// 
        /// 推送消息
        /// 
        /// 频道名称
        /// 消息名称
        /// 数据库
        /// 
        public int PublishMessage(string toChannel, string message, int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.PublishMessage(toChannel, message);
            };
            return TryRedisWrite(fun, db);
        }


        /// 
        /// 创建一个Subscription
        /// 
        /// 
        /// 
        public IRedisSubscription CreateSubscription(int db)
        {
            Func fun = (IRedisClient client) =>
            {
                return client.CreateSubscription();
            };
            return TryRedisWrite(fun, db);
        }
        #endregion

        #region 通用的读写方法

        /// 
        /// 通用读取数据方法
        /// 
        /// 
        /// 
        /// 
        private F TryRedisRead(Func doRead, int db)
        {
            using (PooledRedisClientManager prcm = Managers.Instance().GetManagers(db))
            {

                IRedisClient client = null;
                try
                {
                    using (client = prcm.GetReadOnlyClient())
                    {
                        return doRead(client);
                    }
                }
                catch (RedisException ex)
                {
                    if (DateTime.Now > Monitor_RedisStatusDateTime)
                    {
                        string SystemErrorEmailTo = TCConfigManager.GetConfig("SystemErrorEmailTo");
                        EmailCommom.SendEmail(SystemErrorEmailTo, "", "RedisErr", ex.Message, "", "");
                        FileLog.AddLog("Redis_TryRedisRead", ex.Message);
                        Monitor_RedisStatusDateTime = DateTime.Now.AddMinutes(30);
                    }
                    return default(F);
                }
                finally
                {
                    if (client != null)
                    {
                        prcm.Dispose();
                        client.Dispose();
                    }
                }
            }
        }

        private static DateTime Monitor_RedisStatusDateTime = DateTime.Now;

        /// 
        /// 通用写入数据方法
        /// 
        /// 
        /// 
        /// 
        private F TryRedisWrite(Func doWrite, int db)
        {

            using (PooledRedisClientManager prcm = Managers.Instance().GetManagers(db))
            {

                IRedisClient client = null;
                try
                {
                    using (client = prcm.GetClient())
                    {
                        return doWrite(client);
                    }
                }
                catch (RedisException ex)
                {
                    if (DateTime.Now > Monitor_RedisStatusDateTime)
                    {
                        string SystemErrorEmailTo = TCConfigManager.GetConfig("SystemErrorEmailTo");
                        EmailCommom.SendEmail(SystemErrorEmailTo, "", "RedisErr", ex.Message, "", "");
                        FileLog.AddLog("Redis_TryRedisWrite", ex.Message);
                        Monitor_RedisStatusDateTime = DateTime.Now.AddMinutes(30);
                    }
                    return default(F);
                }
                finally
                {
                    if (client != null)
                    {
                        prcm.Dispose();
                        client.Dispose();
                    }
                }
            }
        }

        #endregion

    }

}

//
https://files.cnblogs.com/files/yyyuguo/Redis.zip

  

C# Redis应用

标签:int   主键   eth   var   reac   消息   nta   mha   util   

原文地址:https://www.cnblogs.com/yyyuguo/p/8426895.html


评论


亲,登录后才可以留言!