• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#redis客户端帮助类

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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

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

        /// <summary>
        ///  //加載配置文件
        /// </summary>
        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的節");
            }
        }

        /// <summary>
        /// redis客戶端
        /// </summary>
        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();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="OpenPooledRedis">是否开启缓冲池</param>
        public RedisTool(bool OpenPooledRedis = false)
        {
            if (OpenPooledRedis)
            {
                //prcm = CreateManager(new[] { "[email protected]:6380" }, new[] { "[email protected]:6380" });
                prcm = CreateManager(new[] { PooledRedisDB1 }, new[] { PooledRedisDB1 });
                Redis = prcm.GetClient() as RedisClient;
            }
        }

        #region Key/Value存储

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存建</param>
        /// <param name="t">缓存值</param>
        /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间</param>
        /// <returns></returns>
        public bool Set<T>(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));
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            return Redis.Get<T>(key);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            return Redis.Remove(key);
        }

        public bool Add<T>(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 链表操作

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

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

        /// <summary>
        /// 获取链表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <returns></returns>
        public IEnumerable<T> GetList<T>(string listId)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            return iredisClient.Lists[listId];
        }

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

        /// <summary>
        /// 根据lambada表达式删除符合条件的实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="func"></param>
        public void RemoveEntityFromList<T>(string listId, Func<T, bool> func)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            IRedisList<T> 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();
        }

        /// <summary>
        /// 缓冲池
        /// </summary>
        /// <param name="readWriteHosts"></param>
        /// <param name="readOnlyHosts"></param>
        /// <returns></returns>
        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) }; 
        }
    }

}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#类的静态成员发布时间:2022-07-10
下一篇:
C#列数据、消息框messagebox、文本按指定长度自动换行发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap