C# redis客户端帮助类

2021-02-07 07:18

阅读:643

标签:帮助   contain   instance   disco   only   配置   缓冲池   entry   ring   

需要在NuGet里面引用ServiceStack.Redis

using ServiceStack.Redis;
using ServiceStack.Redis.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleRedisTest
{
    /// 
    /// 需要在AppSettings裡面配置redis連接字符串節點,名稱固定為“redisHost”
    /// 例如,格式參考 value="server=192.168.31.42;port=6380;password=pisenmaster;db=9" 
    /// 
    public class RedisTool : IDisposable
    {

        /// 
        /// redis主機ip
        /// 
        private readonly static string RedisServerIP = string.Empty;// "192.168.31.42";
        /// 
        /// 連接端口
        /// 
        private readonly static int RedisPort = 0;// 6380;
        /// 
        /// 連接密碼
        /// 
        private readonly static string RedisConnectPassword = string.Empty;// "pisenmaster";
        /// 
        /// 缓冲池 實例db
        /// 
        private readonly static string PooledRedisDB1 = string.Empty;// "pisenmaster@192.168.31.42:6380";

        //默认缓存过期时间单位秒
        public const int secondsTimeOut = 60 * 60;

        /// 
        ///  //加載配置文件
        /// 
        static RedisTool()
        {
            string conStr = System.Configuration.ConfigurationManager.AppSettings["redisHost"];
            try
            {
                if (string.IsNullOrWhiteSpace(conStr))
                {
                    throw new Exception("讀取配置文件出錯,AppSettings節沒有配置名為redisHost的redis連接字符串");
                }
                string[] arr = conStr.Split(;);
                RedisServerIP = arr.First(w => w.ToLower().Contains("server="))?.Split(=)[1];
                RedisPort = Convert.ToInt32(arr.First(w => w.ToLower().Contains("port="))?.Split(=)[1]);
                RedisConnectPassword = arr.First(w => w.ToLower().Contains("password="))?.Split(=)[1];
                PooledRedisDB1 = $"{RedisConnectPassword}@{RedisServerIP}:{RedisPort}";
            }
            catch (Exception ex)
            {
                throw new Exception("讀取配置文件出錯,AppSettings節裡面沒有配置redis連接字符串名為redisHost的節");
            }
        }

        /// 
        /// redis客戶端
        /// 
        public RedisClient Redis = new RedisClient(RedisServerIP, RedisPort, RedisConnectPassword, 9);
        //public RedisClient Redis = new RedisClient("192.168.31.42", 6380, "pisenmaster", 9);

        //缓存池
        private PooledRedisClientManager prcm = new PooledRedisClientManager();

        /// 
        /// 构造函数
        /// 
        /// 是否开启缓冲池
        public RedisTool(bool OpenPooledRedis = false)
        {
            if (OpenPooledRedis)
            {
                //prcm = CreateManager(new[] { "pisenmaster@192.168.31.42:6380" }, new[] { "pisenmaster@192.168.31.42:6380" });
                prcm = CreateManager(new[] { PooledRedisDB1 }, new[] { PooledRedisDB1 });
                Redis = prcm.GetClient() as RedisClient;
            }
        }

        #region Key/Value存储

        /// 
        /// 设置缓存
        /// 
        /// 
        /// 缓存建
        /// 缓存值
        /// 过期时间,单位秒,-1:不过期,0:默认过期时间
        /// 
        public bool Set(string key, T t, int timeout = 0)
        {
            if (timeout 0)
            {
                //永不過期
                return Redis.Set(key, t);
            }
            if (timeout == 0)
            {
                //默認時長
                timeout = secondsTimeOut;
            }
            return Redis.Set(key, t, TimeSpan.FromSeconds(timeout));
        }

        /// 
        /// 获取
        /// 
        /// 
        /// 
        /// 
        public T Get(string key)
        {
            return Redis.Get(key);
        }

        /// 
        /// 删除
        /// 
        /// 
        /// 
        public bool Remove(string key)
        {
            return Redis.Remove(key);
        }

        public bool Add(string key, T t, int timeout)
        {
            if (timeout 0)
            {
                //永不過期
                return Redis.Set(key, t);
            }
            if (timeout == 0)
            {
                //默認時長
                timeout = secondsTimeOut;
            }
            return Redis.Add(key, t, TimeSpan.FromSeconds(timeout));
        }

        #endregion

        #region 链表操作

        /// 
        /// 根据IEnumerable数据添加链表
        /// 
        /// 
        /// 
        /// 
        /// 
        public void AddList(string listId, IEnumerable values, int timeout = 0)
        {
            IRedisTypedClient iredisClient = Redis.As();
            IRedisList redisList = iredisClient.Lists[listId];
            redisList.AddRange(values);
            if (timeout >= 0)
            {
                if (timeout == 0)
                {
                    timeout = secondsTimeOut;
                }
                Redis.ExpireEntryIn(listId, TimeSpan.FromSeconds(timeout));
            }
            iredisClient.Save();
        }

        /// 
        /// 添加单个实体到链表中
        /// 
        /// 
        /// 
        /// 
        /// 過期時間會覆蓋列表之前的過期時間,為-1時保持先前的過期設置
        public void AddEntityToList(string listId, T Item, int timeout = 0)
        {
            IRedisTypedClient iredisClient = Redis.As();
            IRedisList redisList = iredisClient.Lists[listId];
            redisList.Add(Item);
            if (timeout >= 0)
            {
                if (timeout == 0)
                {
                    timeout = secondsTimeOut;
                }
                Redis.ExpireEntryIn(listId, TimeSpan.FromSeconds(timeout));
            }
            iredisClient.Save();
        }

        /// 
        /// 获取链表
        /// 
        /// 
        /// 
        /// 
        public IEnumerable GetList(string listId)
        {
            IRedisTypedClient iredisClient = Redis.As();
            return iredisClient.Lists[listId];
        }

        /// 
        /// 在链表中删除单个实体
        /// 
        /// 
        /// 
        /// 
        public void RemoveEntityFromList(string listId, T t)
        {
            IRedisTypedClient iredisClient = Redis.As();
            IRedisList redisList = iredisClient.Lists[listId];
            redisList.RemoveValue(t);
            iredisClient.Save();
        }

        /// 
        /// 根据lambada表达式删除符合条件的实体
        /// 
        /// 
        /// 
        /// 
        public void RemoveEntityFromList(string listId, Funcbool> func)
        {
            IRedisTypedClient iredisClient = Redis.As();
            IRedisList redisList = iredisClient.Lists[listId];
            T value = redisList.Where(func).FirstOrDefault();
            redisList.RemoveValue(value);
            iredisClient.Save();
        }

        #endregion

        #region 清空Redis所有数据库中的所有key
        public void Flushall()
        {
            Redis.FlushAll();
        }
        #endregion

        //释放资源
        public void Dispose()
        {
            if (Redis != null)
            {
                Redis.Dispose();
                Redis = null;
            }
            GC.Collect();
        }

        /// 
        /// 缓冲池
        /// 
        /// 
        /// 
        /// 
        public static PooledRedisClientManager CreateManager(
        string[] readWriteHosts, string[] readOnlyHosts)
        {
            return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,
            new RedisClientManagerConfig
            {
                MaxWritePoolSize = readWriteHosts.Length * 5,
                MaxReadPoolSize = readOnlyHosts.Length * 5,
                AutoStart = true,
            });
            // { RedisClientFactory = (IRedisClientFactory)RedisCacheClientFactory.Instance.CreateRedisClient("127.0.0.1", 6379) }; 
        }
    }

}

 

C# redis客户端帮助类

标签:帮助   contain   instance   disco   only   配置   缓冲池   entry   ring   

原文地址:https://www.cnblogs.com/youmingkuang/p/11387322.html


评论


亲,登录后才可以留言!