C# 使用 ServiceStack.Redis 自由切换db

之前系统需要引入nodb  想了想最后还是选了 redis

百度一下找了一个RedisCacheHelper.cs 拿过来就用了。

用的时候呢发现一些问题

1.这个方法里面没有找到自由切换库的地方。

2.可不可以通过模糊搜索得到 key 或者 val?

不同业务应该放在不同库里面,这样就不用一股脑的全往db0里面塞了。

既然没找到那就找其他办法呗,想了想,死方法,将key存入的时候加个前缀,不同业务加不同前缀。

由于那会也不知道可不可以通过模糊搜索来得到key。

取的时候就痛苦了。。。每次都是拿出来全部的key。。然后遍历 判断 哎有点难受

今天花时间研究了下,上面两个问题,都解决了,过程有点小曲折,也是断断续续的在弄最终把github上的源码down了,翻了翻代码

https://github.com/ServiceStack/ServiceStack.Redis   这是github的地址

先上我改了之后的代码吧(原版的代码是从哪里来的 忘了...) 有些注释有点问题 看看就好了 我也没仔细改

配置文件中的

 <add key="SessionExpireMinutes" value="180" />
    <add key="RedisServerSession" value="123456@127.0.0.1:6379" />
    <add key="RedisMaxReadPool" value="3" />
    <add key="RedisMaxWritePool" value="1" />
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 public class RedisCacheHelper
    {
        private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] redisHosts = null;
        public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["RedisMaxReadPool"]);
        public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["RedisMaxWritePool"]);

        static RedisCacheHelper()
        {
            var redisHostStr = ConfigurationManager.AppSettings["RedisServerSession"];

            if (!string.IsNullOrEmpty(redisHostStr))
            {
                redisHosts = redisHostStr.Split(',');

                if (redisHosts.Length > 0)
                {
                    pool = new PooledRedisClientManager(redisHosts, redisHosts,
                        new RedisClientManagerConfig()
                        {
                            MaxWritePoolSize = RedisMaxWritePool,
                            MaxReadPoolSize = RedisMaxReadPool,
                            AutoStart = true,
                             
                        });
                    //pool = new PooledRedisClientManager(1,redisHosts);

                }
            }
        }
        public static bool Add<T>(string key, T value, DateTime expiry, int db = 0)
        {
            if (value == null)
            {
                return false;
            }

            if (expiry <= DateTime.Now)
            {
                Remove(key, db);

                return false;
            }

            try
            {
                if (pool != null)
                {
                    //using (var r = pool.GetClient())
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {

                            r.ChangeDb(db);//切换db
                            //r.Db = db;//用r.Db=db;//不管用 也不算不管用吧 它入库的数据 跟 我想让入的库不一样 比如我想入1库 3库 它可能入的是1 0 库 具体我也忘了,反正就是不对劲..

                            //r.FlushDb();
                            r.SendTimeout = 1000;
                            
                            r.Set(key, value, expiry - DateTime.Now);
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    return false;

                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
                return false;
            }

        }

        public static bool Add<T>(string key, T value, TimeSpan slidingExpiration, int db = 0)
        {
            if (value == null)
            {
                return false;
            }

            if (slidingExpiration.TotalSeconds <= 0)
            {
                Remove(key, db);

                return false;
            }

            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);

                            r.SendTimeout = 1000;
                            r.Set(key, value, slidingExpiration);
                            return true;
                        }
                        return false;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
                return false;
            }

        }


        /// <summary>
        /// 获取key对应的val
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static T Get<T>(string key, int db = 0)
        {
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }

            T obj = default(T);

            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);

                            r.SendTimeout = 1000;
                            obj = r.Get<T>(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
            }

            return obj;
        }
        /// <summary>
        /// 获取多个key的value值
        /// </summary>
        public List<T> Get<T>(List<string> keys, int db = 0)
        {
            if (keys == null || keys.Count == 0)
            {
                return default(List<T>);
            }

            List<T> obj = default(List<T>);

            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);

                            r.SendTimeout = 1000;
                            obj = r.GetValues<T>(keys);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", keys);
            }
            return obj;

        }

        public static bool Remove(string key, int db = 0)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);

                            r.SendTimeout = 1000;

                            r.Remove(key);
                            return true;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
                return false;
            }

        }
        public static bool RemoveAll(List<string> key, int db = 0)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);

                            r.SendTimeout = 1000;

                            r.RemoveAll(key);
                            return true;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
                return false;


            }

        }

        /// <summary>
        /// 存在 返回true 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsExists(string key, int db = 0)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);

                            r.SendTimeout = 1000;
                            return r.ContainsKey(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
            }

            return false;
        }
        /// <summary>
        /// 获取所有的key
        /// </summary>
        /// <returns></returns>
        public static List<string> GetAllKey(int db = 0)
        {

            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);


                            return r.GetAllKeys();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!", "cache", "GetAllKey");
            }
            return null;

        }
        /// <summary>
        /// 获取某个库的所有键的 大小 也就是某个库已经存了多少个键
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public static long GetCount(int db = 0)
        {

            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            //r.Db = db;
                            r.ChangeDb(db);

                            return r.DbSize;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!", "cache", "GetCount");
            }
            return 0;

        }

        /// <summary>
        /// 获取 某个开头的key   SearchKey("list*")
        /// </summary>
        /// <param name="key"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static List<string> SearchKey(string key, int db = 0)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = (RedisClient)pool.GetClient())
                    {
                        if (r != null)
                        {
                            
                            //r.Db = db;
                            r.ChangeDb(db);

                            return r.SearchKeys(key);

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
            }

            return null;
        }
    }

首先初始化的时候有个参数,默认库.这个你知道就行了 跟切换库没啥关系

主要是这个

r.ChangeDb(db);

我刚开始用的是r.Db=1;这种 但是确实有问题 你们没事可以去试试 我试了很多次 反正就是不对 达不到你想要的东西

后面去源码里面看了一下

有个HasConnected 估计这个拦截了  转到定义 又引用了socket的东西 继续转到定义 其实也不用转到定义了 socket 我这里应该是没有用到的

另外还有个ChangeDb方法 应该是可以通过手动调用ChangeDb方法来做到

由于之前var r = pool.GetClient();r是调不到ChangeDb方法的

记得将r转一下类型

可以从下载到的github源码中翻翻代码

由于他这个是一个完整的解决方案,所以会有很多测试用例的,测试用例嘛,所有的功能 api都应该是有的,自己可以没事多翻翻,当前代码就是在测试用例里面找到的。

ok,万事大吉                    using (var r = pool.GetClient())     =>                using (var r = (RedisClient)pool.GetClient())

然后r.ChangeDb(123)就完事了

测试了一下,没有问题。

继续看下一个问题 模糊搜索key

https://bbs.csdn.net/topics/392016372 看到了这篇文章

return r.SearchKeys(key); //返回的结果是  模糊搜索的key 自己可以去试试

另外就是想获取到 某个库中所有的键 数量

找了半天  后面发现 直接r.DbSize 就完事了 手动吐血

没事 可以去翻翻下载到的github的源码,应该还会有很多没有用到的功能的

另外我把我现在用到的4个dll都打包放上来吧。已经去除每个小时6000次的限制,如果你觉得dll不靠谱,你也可以手动编译github的代码 把6000那个限制去掉,然后引入到自己项目中去

资源正在审核,等到审核通过我在将地址放出来

https://download.csdn.net/download/u010067685/11633091

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值