redis缓存搭建

  1. </pre><pre name="code" class="csharp">/// <summary>  
  2. /// Redis 帮助类文件  
  3. /// </summary>  
  4. public class RedisHelper : IDisposable {  
  5.     /// <summary>  
  6.     /// 针对Log4net的实例  
  7.     /// </summary>  
  8.     private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);  
  9.   
  10.     /// <summary>  
  11.     /// The seconds time out.  
  12.     /// 默认缓存过期时间单位秒  
  13.     /// </summary>  
  14.     private int secondsTimeOut = 24 * 60 * 60;  
  15.   
  16.     /// <summary>  
  17.     /// 给某个键对应的数据设置过期时间  
  18.     /// </summary>  
  19.     /// <param name="key">键</param>  
  20.     /// <param name="seconds">过期时间</param>  
  21.     public void Expire(string key, int seconds) {  
  22.         try {  
  23.             this.redis.Expire(key, seconds);  
  24.         } catch(Exception ex) {  
  25.             var message = string.Format("设置过期时间出错");  
  26.             Logger.Error(message, ex);  
  27.         }  
  28.     }  
  29.   
  30.     /// <summary>  
  31.     /// 释放资源  
  32.     /// </summary>  
  33.     public void Dispose() {  
  34.         if(this.redis != null) {  
  35.             this.redis.Dispose();  
  36.             this.redis = null;  
  37.         }  
  38.   
  39.         GC.Collect();  
  40.     }  
  41.   
  42.     private IEnumerable<string> SplitString(string strSource, string split) {  
  43.         return strSource.Split(split.ToArray());  
  44.     }  
  45.   
  46.     /// <summary>  
  47.     /// 设置单个实体  
  48.     /// </summary>  
  49.     /// <typeparam name="T"></typeparam>  
  50.     /// <param name="key">缓存建</param>  
  51.     /// <param name="t">缓存值</param>  
  52.     /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间:一天</param>  
  53.     public bool Set<T>(string key, T t, int timeout = -1) {  
  54.         try {  
  55.             if(timeout >= 0) {  
  56.                 if(timeout > 0) {  
  57.                     this.secondsTimeOut = timeout;  
  58.                 }  
  59.   
  60.                 var dtTimeOut = DateTime.Now.AddSeconds(this.secondsTimeOut);  
  61.                 return this.redis.Set(key, t, dtTimeOut);  
  62.             }  
  63.   
  64.             return this.redis.Set(key, t);  
  65.         } catch(Exception ex) {  
  66.             string message = string.Format("设置Redis缓存出错");  
  67.             Logger.Error(message, ex);  
  68.         }  
  69.     }  
  70.   
  71.     /// <summary>  
  72.     ///     获取单个实体  
  73.     /// </summary>  
  74.     /// <typeparam name="T">对象类型</typeparam>  
  75.     /// <param name="key">键值</param>  
  76.     public T Get<T>(string key) {  
  77.         try {  
  78.             return this.redis.Get<T>(key);  
  79.         } catch(Exception ex) {  
  80.             string message = string.Format("获取Redis缓存出错");  
  81.             Logger.Error(message, ex);  
  82.         }  
  83.     }  
  84.   
  85.     /// <summary>  
  86.     ///     删除  
  87.     /// </summary>  
  88.     /// <param name="key">键值</param>  
  89.     public bool Remove(string key) {  
  90.         try {  
  91.             return this.redis.Remove(key);  
  92.         } catch(Exception ex) {  
  93.             string message = string.Format("删除Redis缓存出错");  
  94.             Logger.Error(message, ex);  
  95.         }  
  96.     }  
  97.   
  98.     /// <summary>  
  99.     /// 删除所有  
  100.     /// </summary>  
  101.     public void RemoveAll() {  
  102.         var keyList = this.redis.GetAllKeys();  
  103.         this.redis.RemoveAll(keyList);  
  104.     }  
  105.   
  106.     /// <summary>  
  107.     /// 获取Redis的所有key  
  108.     /// </summary>  
  109.     public List<string> ListKey() {  
  110.         return this.redis.GetAllKeys();  
  111.     }  
  112.   
  113.     /// <summary>  
  114.     ///     添加一个对象  
  115.     /// </summary>  
  116.     /// <typeparam name="T">对象类型</typeparam>  
  117.     /// <param name="key">键</param>  
  118.     /// <param name="t"></param>  
  119.     /// <param name="timeout">过期时间(单位为秒) -1:不过期,0:默认过期时间 一天</param>  
  120.     public bool Add<T>(string key, T t, int timeout = -1) {  
  121.         try {  
  122.             if(timeout >= 0) {  
  123.                 if(timeout > 0) {  
  124.                     this.secondsTimeOut = timeout;  
  125.                 }  
  126.   
  127.                 this.redis.Expire(key, this.secondsTimeOut);  
  128.             }  
  129.   
  130.             return this.redis.Add(key, t);  
  131.         } catch(Exception ex) {  
  132.             string message = string.Format("添加Redis缓存出错");  
  133.             Logger.Error(message, ex);  
  134.         }  
  135.     }  
  136.   
  137.     /// <summary>  
  138.     /// 根据IEnumerable数据添加链表  
  139.     /// </summary>  
  140.     /// <typeparam name="T">对象类型</typeparam>  
  141.     /// <param name="key">键</param>  
  142.     /// <param name="values">值</param>  
  143.     /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>  
  144.     public void AddList<T>(string key, IEnumerable<T> values, int timeout = -1) {  
  145.         try {  
  146.             IRedisTypedClient<T> iredisClient = this.redis.As<T>();  
  147.             IRedisList<T> redisList = iredisClient.Lists[key];  
  148.             redisList.AddRange(values);  
  149.             if(timeout > 0) {  
  150.                 if(timeout > 0) {  
  151.                     this.secondsTimeOut = timeout;  
  152.                 }  
  153.   
  154.                 this.redis.Expire(key, this.secondsTimeOut);  
  155.             }  
  156.   
  157.             iredisClient.Save();  
  158.         } catch(Exception ex) {  
  159.             string message = string.Format("添加链表出错");  
  160.             Logger.Error(message, ex);  
  161.         }  
  162.     }  
  163.   
  164.     /// <summary>  
  165.     /// 添加单个实体到链表中  
  166.     /// </summary>  
  167.     /// <typeparam name="T">对象类型</typeparam>  
  168.     /// <param name="key">键</param>  
  169.     /// <param name="Item"></param>  
  170.     /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>  
  171.     public void AddEntityToList<T>(string key, T Item, int timeout = -1) {  
  172.         try {  
  173.             IRedisTypedClient<T> iredisClient = redis.As<T>();  
  174.             IRedisList<T> redisList = iredisClient.Lists[key];  
  175.             redisList.Add(Item);  
  176.             iredisClient.Save();  
  177.             if(timeout >= 0) {  
  178.                 if(timeout > 0) {  
  179.                     this.secondsTimeOut = timeout;  
  180.                 }  
  181.   
  182.                 this.redis.Expire(key, this.secondsTimeOut);  
  183.             }  
  184.         } catch(Exception ex) {  
  185.             string message = string.Format("添加单个的实体到链表中出错");  
  186.             Logger.Error(message, ex);  
  187.         }  
  188.     }  
  189.   
  190.     /// <summary>  
  191.     /// 获取链表  
  192.     /// </summary>  
  193.     /// <typeparam name="T">对象类型</typeparam>  
  194.     /// <param name="key">键</param>  
  195.     public IEnumerable<T> GetList<T>(string key) {  
  196.         try {  
  197.             IRedisTypedClient<T> iredisClient = redis.As<T>();  
  198.             return iredisClient.Lists[key];  
  199.         } catch(Exception ex) {  
  200.             string message = string.Format("获取链表出错");  
  201.             Logger.Error(message, ex);  
  202.         }  
  203.     }  
  204.   
  205.     /// <summary>  
  206.     /// 在链表中删除单个实体  
  207.     /// </summary>  
  208.     /// <typeparam name="T">对象类型</typeparam>  
  209.     /// <param name="key">键</param>  
  210.     public void RemoveEntityFromList<T>(string key, T t) {  
  211.         try {  
  212.             IRedisTypedClient<T> iredisClient = this.redis.As<T>();  
  213.             IRedisList<T> redisList = iredisClient.Lists[key];  
  214.             redisList.RemoveValue(t);  
  215.             iredisClient.Save();  
  216.         } catch(Exception ex) {  
  217.             string message = string.Format("删除链表中的单个实体出错");  
  218.             Logger.Error(message, ex);  
  219.         }  
  220.     }  
  221.   
  222.     /// <summary>  
  223.     /// 根据key移除整个链表  
  224.     /// </summary>  
  225.     /// <param name="key">键</param>  
  226.     public void RemoveAllList<T>(string key) {  
  227.         try {  
  228.             IRedisTypedClient<T> iredisClient = this.redis.As<T>();  
  229.             IRedisList<T> redisList = iredisClient.Lists[key];  
  230.             redisList.RemoveAll();  
  231.             iredisClient.Save();  
  232.         } catch(Exception ex) {  
  233.             string message = string.Format("删除链表集合");  
  234.             Logger.Error(message, ex);  
  235.         }  
  236.     }  
  237. }本文出自GitHub开源网站  
</pre><pre name="code" class="csharp">/// <summary>
/// Redis 帮助类文件
/// </summary>
public class RedisHelper : IDisposable {
    /// <summary>
    /// 针对Log4net的实例
    /// </summary>
    private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
    /// The seconds time out.
    /// 默认缓存过期时间单位秒
    /// </summary>
    private int secondsTimeOut = 24 * 60 * 60;

    /// <summary>
    /// 给某个键对应的数据设置过期时间
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="seconds">过期时间</param>
    public void Expire(string key, int seconds) {
        try {
            this.redis.Expire(key, seconds);
        } catch(Exception ex) {
            var message = string.Format("设置过期时间出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose() {
        if(this.redis != null) {
            this.redis.Dispose();
            this.redis = null;
        }

        GC.Collect();
    }

    private IEnumerable<string> SplitString(string strSource, string split) {
        return strSource.Split(split.ToArray());
    }

    /// <summary>
    /// 设置单个实体
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key">缓存建</param>
    /// <param name="t">缓存值</param>
    /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间:一天</param>
    public bool Set<T>(string key, T t, int timeout = -1) {
        try {
            if(timeout >= 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                var dtTimeOut = DateTime.Now.AddSeconds(this.secondsTimeOut);
                return this.redis.Set(key, t, dtTimeOut);
            }

            return this.redis.Set(key, t);
        } catch(Exception ex) {
            string message = string.Format("设置Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    ///     获取单个实体
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键值</param>
    public T Get<T>(string key) {
        try {
            return this.redis.Get<T>(key);
        } catch(Exception ex) {
            string message = string.Format("获取Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    ///     删除
    /// </summary>
    /// <param name="key">键值</param>
    public bool Remove(string key) {
        try {
            return this.redis.Remove(key);
        } catch(Exception ex) {
            string message = string.Format("删除Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 删除所有
    /// </summary>
    public void RemoveAll() {
        var keyList = this.redis.GetAllKeys();
        this.redis.RemoveAll(keyList);
    }

    /// <summary>
    /// 获取Redis的所有key
    /// </summary>
    public List<string> ListKey() {
        return this.redis.GetAllKeys();
    }

    /// <summary>
    ///     添加一个对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="t"></param>
    /// <param name="timeout">过期时间(单位为秒) -1:不过期,0:默认过期时间 一天</param>
    public bool Add<T>(string key, T t, int timeout = -1) {
        try {
            if(timeout >= 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                this.redis.Expire(key, this.secondsTimeOut);
            }

            return this.redis.Add(key, t);
        } catch(Exception ex) {
            string message = string.Format("添加Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 根据IEnumerable数据添加链表
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="values">值</param>
    /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>
    public void AddList<T>(string key, IEnumerable<T> values, int timeout = -1) {
        try {
            IRedisTypedClient<T> iredisClient = this.redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.AddRange(values);
            if(timeout > 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                this.redis.Expire(key, this.secondsTimeOut);
            }

            iredisClient.Save();
        } catch(Exception ex) {
            string message = string.Format("添加链表出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 添加单个实体到链表中
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="Item"></param>
    /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>
    public void AddEntityToList<T>(string key, T Item, int timeout = -1) {
        try {
            IRedisTypedClient<T> iredisClient = redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.Add(Item);
            iredisClient.Save();
            if(timeout >= 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                this.redis.Expire(key, this.secondsTimeOut);
            }
        } catch(Exception ex) {
            string message = string.Format("添加单个的实体到链表中出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 获取链表
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    public IEnumerable<T> GetList<T>(string key) {
        try {
            IRedisTypedClient<T> iredisClient = redis.As<T>();
            return iredisClient.Lists[key];
        } catch(Exception ex) {
            string message = string.Format("获取链表出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 在链表中删除单个实体
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    public void RemoveEntityFromList<T>(string key, T t) {
        try {
            IRedisTypedClient<T> iredisClient = this.redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.RemoveValue(t);
            iredisClient.Save();
        } catch(Exception ex) {
            string message = string.Format("删除链表中的单个实体出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 根据key移除整个链表
    /// </summary>
    /// <param name="key">键</param>
    public void RemoveAllList<T>(string key) {
        try {
            IRedisTypedClient<T> iredisClient = this.redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.RemoveAll();
            iredisClient.Save();
        } catch(Exception ex) {
            string message = string.Format("删除链表集合");
            Logger.Error(message, ex);
        }
    }
}本文出自GitHub开源网站


=================================

asp.net mvc 用Redis实现分布式集群共享Session

1、这两天研究Redis搞分布式session问题,网上找的资料都是用ServiceStack.Redis来实现的,但是在做性能测试的时候 发现最新的v4版本有限制每小时候最多请求6000次,因为官网开始商业化要收费了,好坑爹的说,还好我前期弄了个性能测试列子,不然上线以后出问题那就 麻烦了。后面找了个NServiceKit.Redis(好像就是ServiceStack.Redis的v3版本)来替代v4的收费版。

2、解决方案是 Redis+cookie方式实现记录用户登录状态

     cookie:存放用户的ID,这个ID是经过加密的,并且后台可以通过密钥解密。

     Redis:key/value 方式存储,key存放比如:user_1。  value存放用户实体对象。

3、先安装一个Redis,windows的版本在本地进行测试,后期上线更换linux系统的Redis替换一下ip就可以了。

4、添加一个Session管理类


  1. public class SessionHelper  
  2.     {  
  3.         private const int secondsTimeOut = 60 * 20;  //默认过期时间20分钟  单位秒  
  4.   
  5.   
  6.         public RedisHelper Redis = new RedisHelper(false);  
  7.         public LoginUserInfo this[string key]  
  8.         {  
  9.             get  
  10.             {  
  11.                 string webCookie = WebHelper.GetCookie(key);  
  12.                 if (webCookie == "")  
  13.                 {  
  14.                     return null;  
  15.                 }  
  16.                 key = key + "_" + SecureHelper.AESDecrypt(webCookie);  
  17.   
  18.                 //距离过期时间还有多少秒  
  19.                 long l = Redis.TTL(key);  
  20.                 if (l >= 0)  
  21.                 {  
  22.                     Redis.Expire(key, secondsTimeOut);  
  23.                 }  
  24.                   
  25.                 return Redis.Get<LoginUserInfo>(key);  
  26.             }  
  27.             set  
  28.             {  
  29.                 SetSession(key, value);  
  30.             }  
  31.         }  
  32.         public void SetSession(string key, LoginUserInfo value)  
  33.         {  
  34.             if (string.IsNullOrWhiteSpace(key))  
  35.             {  
  36.                 throw new Exception("Key is Null or Epmty");  
  37.             }  
  38.             WebHelper.SetCookie(key, SecureHelper.AESEncrypt(value.ID.ToString()));  
  39.             key = key + "_" + value.ID;  
  40.             Redis.Set<LoginUserInfo>(key, value, secondsTimeOut);  
  41.         }  
  42.   
  43.         /// <summary>  
  44.         /// 移除Session  
  45.         /// </summary>  
  46.         /// <param name="key"></param>  
  47.         /// <returns></returns>  
  48.         public bool Remove(string key)  
  49.         {  
  50.             var rs = Redis.Remove(key + "_" + SecureHelper.AESDecrypt(WebHelper.GetCookie(key)));  
  51.             WebHelper.DeleteCookie(key);  
  52.             return rs;  
  53.         }  
  54.                
  55.     }  
  56.   
  57. SessionHelper  
public class SessionHelper
    {
        private const int secondsTimeOut = 60 * 20;  //默认过期时间20分钟  单位秒


        public RedisHelper Redis = new RedisHelper(false);
        public LoginUserInfo this[string key]
        {
            get
            {
                string webCookie = WebHelper.GetCookie(key);
                if (webCookie == "")
                {
                    return null;
                }
                key = key + "_" + SecureHelper.AESDecrypt(webCookie);

                //距离过期时间还有多少秒
                long l = Redis.TTL(key);
                if (l >= 0)
                {
                    Redis.Expire(key, secondsTimeOut);
                }
                
                return Redis.Get<LoginUserInfo>(key);
            }
            set
            {
                SetSession(key, value);
            }
        }
        public void SetSession(string key, LoginUserInfo value)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new Exception("Key is Null or Epmty");
            }
            WebHelper.SetCookie(key, SecureHelper.AESEncrypt(value.ID.ToString()));
            key = key + "_" + value.ID;
            Redis.Set<LoginUserInfo>(key, value, secondsTimeOut);
        }

        /// <summary>
        /// 移除Session
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            var rs = Redis.Remove(key + "_" + SecureHelper.AESDecrypt(WebHelper.GetCookie(key)));
            WebHelper.DeleteCookie(key);
            return rs;
        }
             
    }

SessionHelper
5、Redis操作类
  1. public class RedisHelper : IDisposable  
  2.     {  
  3.        private RedisClient Redis = new RedisClient("127.0.0.1", 6379);  
  4.         //缓存池  
  5.         PooledRedisClientManager prcm = new PooledRedisClientManager();  
  6.   
  7.         //默认缓存过期时间单位秒  
  8.         public int secondsTimeOut = 20 * 60;  
  9.   
  10.         /// <summary>  
  11.         /// 缓冲池  
  12.         /// </summary>  
  13.         /// <param name="readWriteHosts"></param>  
  14.         /// <param name="readOnlyHosts"></param>  
  15.         /// <returns></returns>  
  16.         public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)  
  17.         {  
  18.             return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,  
  19.                 new RedisClientManagerConfig  
  20.                 {  
  21.                     MaxWritePoolSize = readWriteHosts.Length * 5,  
  22.                     MaxReadPoolSize = readOnlyHosts.Length * 5,  
  23.                     AutoStart = true,  
  24.                 });   
  25.         }  
  26.         /// <summary>  
  27.         /// 构造函数  
  28.         /// </summary>  
  29.         /// <param name="OpenPooledRedis">是否开启缓冲池</param>  
  30.         public RedisHelper(bool OpenPooledRedis = false)  
  31.         {  
  32.   
  33.             if (OpenPooledRedis)  
  34.             {  
  35.                 prcm = CreateManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" });  
  36.                 Redis = prcm.GetClient() as RedisClient;  
  37.             }  
  38.         }  
  39.         /// <summary>  
  40.         /// 距离过期时间还有多少秒  
  41.         /// </summary>  
  42.         /// <param name="key"></param>  
  43.         /// <returns></returns>  
  44.         public long TTL(string key)  
  45.         {  
  46.             return Redis.Ttl(key);  
  47.         }  
  48.         /// <summary>  
  49.         /// 设置过期时间  
  50.         /// </summary>  
  51.         /// <param name="key"></param>  
  52.         /// <param name="timeout"></param>  
  53.         public void Expire(string key,int timeout = 0)  
  54.         {  
  55.             if (timeout >= 0)  
  56.             {  
  57.                 if (timeout > 0)  
  58.                 {  
  59.                     secondsTimeOut = timeout;  
  60.                 }  
  61.                 Redis.Expire(key, secondsTimeOut);  
  62.             }  
  63.         }  
  64.  
  65.         #region Key/Value存储  
  66.         /// <summary>  
  67.         /// 设置缓存  
  68.         /// </summary>  
  69.         /// <typeparam name="T"></typeparam>  
  70.         /// <param name="key">缓存建</param>  
  71.         /// <param name="t">缓存值</param>  
  72.         /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间</param>  
  73.         /// <returns></returns>  
  74.         public bool Set<T>(string key, T t, int timeout = 0)  
  75.         {  
  76.             Redis.Set<T>(key, t);  
  77.             if (timeout >= 0)  
  78.             {  
  79.                 if (timeout > 0)  
  80.                 {  
  81.                     secondsTimeOut = timeout;  
  82.                 }  
  83.                 Redis.Expire(key, secondsTimeOut);  
  84.             }  
  85.             return true;  
  86.               
  87.         }  
  88.         /// <summary>  
  89.         /// 获取  
  90.         /// </summary>  
  91.         /// <typeparam name="T"></typeparam>  
  92.         /// <param name="key"></param>  
  93.         /// <returns></returns>  
  94.         public T Get<T>(string key)  
  95.         {  
  96.             return Redis.Get<T>(key);  
  97.         }  
  98.         /// <summary>  
  99.         /// 删除  
  100.         /// </summary>  
  101.         /// <param name="key"></param>  
  102.         /// <returns></returns>  
  103.         public bool Remove(string key)  
  104.         {  
  105.             return Redis.Remove(key);  
  106.         }  
  107.         #endregion  
  108.   
  109.         //释放资源  
  110.         public void Dispose()  
  111.         {  
  112.             if (Redis != null)  
  113.             {  
  114.                 Redis.Dispose();  
  115.                 Redis = null;  
  116.             }  
  117.             GC.Collect();  
  118.   
  119.         }  
  120.     }  
  121.   
  122. RedisHelper  
public class RedisHelper : IDisposable
    {
       private RedisClient Redis = new RedisClient("127.0.0.1", 6379);
        //缓存池
        PooledRedisClientManager prcm = new PooledRedisClientManager();

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

        /// <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,
                }); 
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="OpenPooledRedis">是否开启缓冲池</param>
        public RedisHelper(bool OpenPooledRedis = false)
        {

            if (OpenPooledRedis)
            {
                prcm = CreateManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" });
                Redis = prcm.GetClient() as RedisClient;
            }
        }
        /// <summary>
        /// 距离过期时间还有多少秒
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public long TTL(string key)
        {
            return Redis.Ttl(key);
        }
        /// <summary>
        /// 设置过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="timeout"></param>
        public void Expire(string key,int timeout = 0)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
        }

        #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)
        {
            Redis.Set<T>(key, t);
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
            return true;
            
        }
        /// <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);
        }
        #endregion

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

        }
    }

RedisHelper

用C#封装的ServiceStack.redis操作类

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ServiceStack.Redis;  
  7. namespace TestRedis  
  8. {  
  9.     class RedisHelper:IDisposable  
  10.     {  
  11.         /*copyright@2013 All Rights Reserved 
  12.          * Author:Mars 
  13.          * Date:2013.08.27 
  14.          * QQ:258248340 
  15.          * servicestack.redis为github中的开源项目 
  16.          * redis是一个典型的k/v型数据库 
  17.          * redis共支持五种类型的数据 string,list,hash,set,sortedset 
  18.          *  
  19.          * string是最简单的字符串类型 
  20.          *  
  21.          * list是字符串列表,其内部是用双向链表实现的,因此在获取/设置数据时可以支持正负索引 
  22.          * 也可以将其当做堆栈结构使用 
  23.          *  
  24.          * hash类型是一种字典结构,也是最接近RDBMS的数据类型,其存储了字段和字段值的映射,但字段值只能是 
  25.          * 字符串类型,散列类型适合存储对象,建议使用对象类别和ID构成键名,使用字段表示对象属性,字 
  26.          * 段值存储属性值,例如:car:2 price 500 ,car:2  color black,用redis命令设置散列时,命令格式 
  27.          * 如下:HSET key field value,即key,字段名,字段值 
  28.          *  
  29.          * set是一种集合类型,redis中可以对集合进行交集,并集和互斥运算 
  30.          *            
  31.          * sorted set是在集合的基础上为每个元素关联了一个“分数”,我们能够 
  32.          * 获得分数最高的前N个元素,获得指定分数范围内的元素,元素是不同的,但是"分数"可以是相同的 
  33.          * set是用散列表和跳跃表实现的,获取数据的速度平均为o(log(N)) 
  34.          *  
  35.          * 需要注意的是,redis所有数据类型都不支持嵌套 
  36.          * redis中一般不区分插入和更新操作,只是命令的返回值不同 
  37.          * 在插入key时,如果不存在,将会自动创建 
  38.          *  
  39.          * 在实际生产环境中,由于多线程并发的关系,建议使用连接池,本类只是用于测试简单的数据类型 
  40.          */  
  41.   
  42.         /* 
  43.          * 以下方法为基本的设置数据和取数据 
  44.          */  
  45.         private static RedisClient redisCli = null;  
  46.         /// <summary>  
  47.         /// 建立redis长连接  
  48.         /// </summary>  
  49.         /// 将此处的IP换为自己的redis实例IP,如果设有密码,第三个参数为密码,string 类型  
  50.         public static void CreateClient(string hostIP,int port,string keyword)  
  51.         {  
  52.             if (redisCli == null)  
  53.             {  
  54.                 redisCli = new RedisClient(hostIP, port, keyword);  
  55.             }  
  56.    
  57.         }  
  58.         public static void CreateClient(string hostIP, int port)  
  59.         {  
  60.             if (redisCli == null)  
  61.             {  
  62.                 redisCli = new RedisClient(hostIP, port);  
  63.              }  
  64.    
  65.         }  
  66.         //private static RedisClient redisCli = new RedisClient("192.168.101.165", 6379, "123456");  
  67.         /// <summary>  
  68.         /// 获取key,返回string格式  
  69.         /// </summary>  
  70.         /// <param name="key"></param>  
  71.         /// <returns></returns>  
  72.         public static string getValueString(string key)  
  73.         {  
  74.           
  75.                 string value = redisCli.GetValue(key);  
  76.                 return value;  
  77.              
  78.             
  79.         }  
  80.         /// <summary>  
  81.         /// 获取key,返回byte[]格式  
  82.         /// </summary>  
  83.         /// <param name="key"></param>  
  84.         /// <returns></returns>  
  85.         public static byte[] getValueByte(string key)  
  86.         {  
  87.             byte[] value = redisCli.Get(key);  
  88.             return value;  
  89.         }  
  90.         /// <summary>  
  91.         /// 获得某个hash型key下的所有字段  
  92.         /// </summary>  
  93.         /// <param name="hashId"></param>  
  94.         /// <returns></returns>  
  95.         public static List<string> GetHashFields(string hashId)  
  96.         {  
  97.             List<string> hashFields = redisCli.GetHashKeys(hashId);  
  98.             return hashFields;  
  99.         }  
  100.         /// <summary>  
  101.         /// 获得某个hash型key下的所有值  
  102.         /// </summary>  
  103.         /// <param name="hashId"></param>  
  104.         /// <returns></returns>  
  105.         public static List<string> GetHashValues(string hashId)  
  106.         {  
  107.             List<string> hashValues = redisCli.GetHashKeys(hashId);  
  108.             return hashValues;  
  109.         }  
  110.         /// <summary>  
  111.         /// 获得hash型key某个字段的值  
  112.         /// </summary>  
  113.         /// <param name="key"></param>  
  114.         /// <param name="field"></param>  
  115.         public static string GetHashField(string key, string field)  
  116.         {  
  117.             string value = redisCli.GetValueFromHash(key, field);  
  118.             return value;  
  119.         }  
  120.         /// <summary>  
  121.         /// 设置hash型key某个字段的值  
  122.         /// </summary>  
  123.         /// <param name="key"></param>  
  124.         /// <param name="field"></param>  
  125.         /// <param name="value"></param>  
  126.         public static void SetHashField(string key, string field, string value)  
  127.         {  
  128.             redisCli.SetEntryInHash(key, field, value);  
  129.         }  
  130.         /// <summary>  
  131.         ///使某个字段增加  
  132.         /// </summary>  
  133.         /// <param name="key"></param>  
  134.         /// <param name="field"></param>  
  135.         /// <returns></returns>  
  136.         public static void SetHashIncr(string key, string field, long incre)  
  137.         {  
  138.             redisCli.IncrementValueInHash(key, field, incre);  
  139.   
  140.         }  
  141.         /// <summary>  
  142.         /// 向list类型数据添加成员,向列表底部(右侧)添加  
  143.         /// </summary>  
  144.         /// <param name="Item"></param>  
  145.         /// <param name="list"></param>  
  146.         public static void AddItemToListRight(string list, string item)  
  147.         {  
  148.             redisCli.AddItemToList(list, item);  
  149.         }  
  150.         /// <summary>  
  151.         /// 向list类型数据添加成员,向列表顶部(左侧)添加  
  152.         /// </summary>  
  153.         /// <param name="list"></param>  
  154.         /// <param name="item"></param>  
  155.         public static void AddItemToListLeft(string list, string item)  
  156.         {  
  157.             redisCli.LPush(list, Encoding.Default.GetBytes(item));  
  158.         }  
  159.         /// <summary>  
  160.         /// 从list类型数据读取所有成员  
  161.         /// </summary>  
  162.         public static List<string> GetAllItems(string list)  
  163.         {  
  164.             List<string> listMembers = redisCli.GetAllItemsFromList(list);  
  165.             return listMembers;  
  166.         }  
  167.         /// <summary>  
  168.         /// 从list类型数据指定索引处获取数据,支持正索引和负索引  
  169.         /// </summary>  
  170.         /// <param name="list"></param>  
  171.         /// <returns></returns>  
  172.         public static string GetItemFromList(string list, int index)  
  173.         {  
  174.             string item = redisCli.GetItemFromList(list, index);  
  175.             return item;  
  176.         }  
  177.         /// <summary>  
  178.         /// 向列表底部(右侧)批量添加数据  
  179.         /// </summary>  
  180.         /// <param name="list"></param>  
  181.         /// <param name="values"></param>  
  182.         public static void GetRangeToList(string list, List<string> values)  
  183.         {  
  184.             redisCli.AddRangeToList(list, values);  
  185.         }  
  186.         /// <summary>  
  187.         /// 向集合中添加数据  
  188.         /// </summary>  
  189.         /// <param name="item"></param>  
  190.         /// <param name="set"></param>  
  191.         public static void GetItemToSet(string item, string set)  
  192.         {  
  193.             redisCli.AddItemToSet(item, set);  
  194.         }  
  195.         /// <summary>  
  196.         /// 获得集合中所有数据  
  197.         /// </summary>  
  198.         /// <param name="set"></param>  
  199.         /// <returns></returns>  
  200.         public static HashSet<string> GetAllItemsFromSet(string set)  
  201.         {  
  202.             HashSet<string> items = redisCli.GetAllItemsFromSet(set);  
  203.             return items;  
  204.         }  
  205.         /// <summary>  
  206.         /// 获取fromSet集合和其他集合不同的数据  
  207.         /// </summary>  
  208.         /// <param name="fromSet"></param>  
  209.         /// <param name="toSet"></param>  
  210.         /// <returns></returns>  
  211.         public static HashSet<string> GetSetDiff(string fromSet, params string[] toSet)  
  212.         {  
  213.             HashSet<string> diff = redisCli.GetDifferencesFromSet(fromSet, toSet);  
  214.             return diff;  
  215.         }  
  216.         /// <summary>  
  217.         /// 获得所有集合的并集  
  218.         /// </summary>  
  219.         /// <param name="set"></param>  
  220.         /// <returns></returns>  
  221.         public static HashSet<string> GetSetUnion(params string[] set)  
  222.         {  
  223.             HashSet<string> union = redisCli.GetUnionFromSets(set);  
  224.             return union;  
  225.         }  
  226.         /// <summary>  
  227.         /// 获得所有集合的交集  
  228.         /// </summary>  
  229.         /// <param name="set"></param>  
  230.         /// <returns></returns>  
  231.         public static HashSet<string> GetSetInter(params string[] set)  
  232.         {  
  233.             HashSet<string> inter = redisCli.GetIntersectFromSets(set);  
  234.             return inter;  
  235.         }  
  236.         /// <summary>  
  237.         /// 向有序集合中添加元素  
  238.         /// </summary>  
  239.         /// <param name="set"></param>  
  240.         /// <param name="value"></param>  
  241.         /// <param name="score"></param>  
  242.         public static void AddItemToSortedSet(string set,string value,long score)  
  243.         {  
  244.             redisCli.AddItemToSortedSet(set,value,score);  
  245.         }  
  246.         /// <summary>  
  247.         /// 获得某个值在有序集合中的排名,按分数的降序排列  
  248.         /// </summary>  
  249.         /// <param name="set"></param>  
  250.         /// <param name="value"></param>  
  251.         /// <returns></returns>  
  252.         public static int GetItemIndexInSortedSetDesc(string setstring value)  
  253.         {  
  254.             int index = redisCli.GetItemIndexInSortedSetDesc(set, value);  
  255.             return index;  
  256.         }  
  257.         /// <summary>  
  258.         /// 获得某个值在有序集合中的排名,按分数的升序排列  
  259.         /// </summary>  
  260.         /// <param name="set"></param>  
  261.         /// <param name="value"></param>  
  262.         /// <returns></returns>  
  263.         public static int GetItemIndexInSortedSet(string setstring value)  
  264.         {  
  265.             int index = redisCli.GetItemIndexInSortedSet(set, value);  
  266.             return index;  
  267.         }  
  268.         /// <summary>  
  269.         /// 获得有序集合中某个值得分数  
  270.         /// </summary>  
  271.         /// <param name="set"></param>  
  272.         /// <param name="value"></param>  
  273.         /// <returns></returns>  
  274.         public static double GetItemScoreInSortedSet(string setstring value)  
  275.         {  
  276.             double score = redisCli.GetItemScoreInSortedSet(set, value);  
  277.             return score;  
  278.         }  
  279.         /// <summary>  
  280.         /// 获得有序集合中,某个排名范围的所有值  
  281.         /// </summary>  
  282.         /// <param name="set"></param>  
  283.         /// <param name="beginRank"></param>  
  284.         /// <param name="endRank"></param>  
  285.         /// <returns></returns>  
  286.         public static List<string> GetRangeFromSortedSet(string set,int beginRank, int endRank)  
  287.         {  
  288.             List<string> valueList=redisCli.GetRangeFromSortedSet(set,beginRank,endRank);  
  289.             return valueList;  
  290.         }  
  291.         /// <summary>  
  292.         /// 获得有序集合中,某个分数范围内的所有值,升序  
  293.         /// </summary>  
  294.         /// <param name="set"></param>  
  295.         /// <param name="beginScore"></param>  
  296.         /// <param name="endScore"></param>  
  297.         /// <returns></returns>  
  298.         public static List<string> GetRangeFromSortedSet(string setdouble beginScore, double endScore)  
  299.         {  
  300.             List<string> valueList = redisCli.GetRangeFromSortedSetByHighestScore(set, beginScore, endScore);  
  301.             return valueList;  
  302.         }  
  303.         /// <summary>  
  304.         /// 获得有序集合中,某个分数范围内的所有值,降序  
  305.         /// </summary>  
  306.         /// <param name="set"></param>  
  307.         /// <param name="beginScore"></param>  
  308.         /// <param name="endScore"></param>  
  309.         /// <returns></returns>  
  310.         public static List<string> GetRangeFromSortedSetDesc(string setdouble beginScore, double endScore)  
  311.         {  
  312.             List<string> vlaueList=redisCli.GetRangeFromSortedSetByLowestScore(set,beginScore,endScore);  
  313.             return vlaueList;  
  314.         }  
  315.         public void Dispose()  
  316.         {  
  317.             redisCli.Dispose();  
  318.         }  
  319.    
  320.     }  
  321. }  
  322.   
  323. RedisHelper  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;
namespace TestRedis
{
    class RedisHelper:IDisposable
    {
        /*copyright@2013 All Rights Reserved
         * Author:Mars
         * Date:2013.08.27
         * QQ:258248340
         * servicestack.redis为github中的开源项目
         * redis是一个典型的k/v型数据库
         * redis共支持五种类型的数据 string,list,hash,set,sortedset
         * 
         * string是最简单的字符串类型
         * 
         * list是字符串列表,其内部是用双向链表实现的,因此在获取/设置数据时可以支持正负索引
         * 也可以将其当做堆栈结构使用
         * 
         * hash类型是一种字典结构,也是最接近RDBMS的数据类型,其存储了字段和字段值的映射,但字段值只能是
         * 字符串类型,散列类型适合存储对象,建议使用对象类别和ID构成键名,使用字段表示对象属性,字
         * 段值存储属性值,例如:car:2 price 500 ,car:2  color black,用redis命令设置散列时,命令格式
         * 如下:HSET key field value,即key,字段名,字段值
         * 
         * set是一种集合类型,redis中可以对集合进行交集,并集和互斥运算
         *           
         * sorted set是在集合的基础上为每个元素关联了一个“分数”,我们能够
         * 获得分数最高的前N个元素,获得指定分数范围内的元素,元素是不同的,但是"分数"可以是相同的
         * set是用散列表和跳跃表实现的,获取数据的速度平均为o(log(N))
         * 
         * 需要注意的是,redis所有数据类型都不支持嵌套
         * redis中一般不区分插入和更新操作,只是命令的返回值不同
         * 在插入key时,如果不存在,将会自动创建
         * 
         * 在实际生产环境中,由于多线程并发的关系,建议使用连接池,本类只是用于测试简单的数据类型
         */

        /*
         * 以下方法为基本的设置数据和取数据
         */
        private static RedisClient redisCli = null;
        /// <summary>
        /// 建立redis长连接
        /// </summary>
        /// 将此处的IP换为自己的redis实例IP,如果设有密码,第三个参数为密码,string 类型
        public static void CreateClient(string hostIP,int port,string keyword)
        {
            if (redisCli == null)
            {
                redisCli = new RedisClient(hostIP, port, keyword);
            }
 
        }
        public static void CreateClient(string hostIP, int port)
        {
            if (redisCli == null)
            {
                redisCli = new RedisClient(hostIP, port);
             }
 
        }
        //private static RedisClient redisCli = new RedisClient("192.168.101.165", 6379, "123456");
        /// <summary>
        /// 获取key,返回string格式
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string getValueString(string key)
        {
        
                string value = redisCli.GetValue(key);
                return value;
           
          
        }
        /// <summary>
        /// 获取key,返回byte[]格式
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] getValueByte(string key)
        {
            byte[] value = redisCli.Get(key);
            return value;
        }
        /// <summary>
        /// 获得某个hash型key下的所有字段
        /// </summary>
        /// <param name="hashId"></param>
        /// <returns></returns>
        public static List<string> GetHashFields(string hashId)
        {
            List<string> hashFields = redisCli.GetHashKeys(hashId);
            return hashFields;
        }
        /// <summary>
        /// 获得某个hash型key下的所有值
        /// </summary>
        /// <param name="hashId"></param>
        /// <returns></returns>
        public static List<string> GetHashValues(string hashId)
        {
            List<string> hashValues = redisCli.GetHashKeys(hashId);
            return hashValues;
        }
        /// <summary>
        /// 获得hash型key某个字段的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="field"></param>
        public static string GetHashField(string key, string field)
        {
            string value = redisCli.GetValueFromHash(key, field);
            return value;
        }
        /// <summary>
        /// 设置hash型key某个字段的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        public static void SetHashField(string key, string field, string value)
        {
            redisCli.SetEntryInHash(key, field, value);
        }
        /// <summary>
        ///使某个字段增加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static void SetHashIncr(string key, string field, long incre)
        {
            redisCli.IncrementValueInHash(key, field, incre);

        }
        /// <summary>
        /// 向list类型数据添加成员,向列表底部(右侧)添加
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="list"></param>
        public static void AddItemToListRight(string list, string item)
        {
            redisCli.AddItemToList(list, item);
        }
        /// <summary>
        /// 向list类型数据添加成员,向列表顶部(左侧)添加
        /// </summary>
        /// <param name="list"></param>
        /// <param name="item"></param>
        public static void AddItemToListLeft(string list, string item)
        {
            redisCli.LPush(list, Encoding.Default.GetBytes(item));
        }
        /// <summary>
        /// 从list类型数据读取所有成员
        /// </summary>
        public static List<string> GetAllItems(string list)
        {
            List<string> listMembers = redisCli.GetAllItemsFromList(list);
            return listMembers;
        }
        /// <summary>
        /// 从list类型数据指定索引处获取数据,支持正索引和负索引
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetItemFromList(string list, int index)
        {
            string item = redisCli.GetItemFromList(list, index);
            return item;
        }
        /// <summary>
        /// 向列表底部(右侧)批量添加数据
        /// </summary>
        /// <param name="list"></param>
        /// <param name="values"></param>
        public static void GetRangeToList(string list, List<string> values)
        {
            redisCli.AddRangeToList(list, values);
        }
        /// <summary>
        /// 向集合中添加数据
        /// </summary>
        /// <param name="item"></param>
        /// <param name="set"></param>
        public static void GetItemToSet(string item, string set)
        {
            redisCli.AddItemToSet(item, set);
        }
        /// <summary>
        /// 获得集合中所有数据
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static HashSet<string> GetAllItemsFromSet(string set)
        {
            HashSet<string> items = redisCli.GetAllItemsFromSet(set);
            return items;
        }
        /// <summary>
        /// 获取fromSet集合和其他集合不同的数据
        /// </summary>
        /// <param name="fromSet"></param>
        /// <param name="toSet"></param>
        /// <returns></returns>
        public static HashSet<string> GetSetDiff(string fromSet, params string[] toSet)
        {
            HashSet<string> diff = redisCli.GetDifferencesFromSet(fromSet, toSet);
            return diff;
        }
        /// <summary>
        /// 获得所有集合的并集
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static HashSet<string> GetSetUnion(params string[] set)
        {
            HashSet<string> union = redisCli.GetUnionFromSets(set);
            return union;
        }
        /// <summary>
        /// 获得所有集合的交集
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static HashSet<string> GetSetInter(params string[] set)
        {
            HashSet<string> inter = redisCli.GetIntersectFromSets(set);
            return inter;
        }
        /// <summary>
        /// 向有序集合中添加元素
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <param name="score"></param>
        public static void AddItemToSortedSet(string set,string value,long score)
        {
            redisCli.AddItemToSortedSet(set,value,score);
        }
        /// <summary>
        /// 获得某个值在有序集合中的排名,按分数的降序排列
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int GetItemIndexInSortedSetDesc(string set, string value)
        {
            int index = redisCli.GetItemIndexInSortedSetDesc(set, value);
            return index;
        }
        /// <summary>
        /// 获得某个值在有序集合中的排名,按分数的升序排列
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int GetItemIndexInSortedSet(string set, string value)
        {
            int index = redisCli.GetItemIndexInSortedSet(set, value);
            return index;
        }
        /// <summary>
        /// 获得有序集合中某个值得分数
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static double GetItemScoreInSortedSet(string set, string value)
        {
            double score = redisCli.GetItemScoreInSortedSet(set, value);
            return score;
        }
        /// <summary>
        /// 获得有序集合中,某个排名范围的所有值
        /// </summary>
        /// <param name="set"></param>
        /// <param name="beginRank"></param>
        /// <param name="endRank"></param>
        /// <returns></returns>
        public static List<string> GetRangeFromSortedSet(string set,int beginRank, int endRank)
        {
            List<string> valueList=redisCli.GetRangeFromSortedSet(set,beginRank,endRank);
            return valueList;
        }
        /// <summary>
        /// 获得有序集合中,某个分数范围内的所有值,升序
        /// </summary>
        /// <param name="set"></param>
        /// <param name="beginScore"></param>
        /// <param name="endScore"></param>
        /// <returns></returns>
        public static List<string> GetRangeFromSortedSet(string set, double beginScore, double endScore)
        {
            List<string> valueList = redisCli.GetRangeFromSortedSetByHighestScore(set, beginScore, endScore);
            return valueList;
        }
        /// <summary>
        /// 获得有序集合中,某个分数范围内的所有值,降序
        /// </summary>
        /// <param name="set"></param>
        /// <param name="beginScore"></param>
        /// <param name="endScore"></param>
        /// <returns></returns>
        public static List<string> GetRangeFromSortedSetDesc(string set, double beginScore, double endScore)
        {
            List<string> vlaueList=redisCli.GetRangeFromSortedSetByLowestScore(set,beginScore,endScore);
            return vlaueList;
        }
        public void Dispose()
        {
            redisCli.Dispose();
        }
 
    }
}

RedisHelper

==========================================

Redis主从服务部署

Redis服务器及应用

基于Redis缓存的Session共享(附源码)

基于redis实现分布式Session

  1. </pre><pre name="code" class="csharp">/// <summary>  
  2. /// Redis 帮助类文件  
  3. /// </summary>  
  4. public class RedisHelper : IDisposable {  
  5.     /// <summary>  
  6.     /// 针对Log4net的实例  
  7.     /// </summary>  
  8.     private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);  
  9.   
  10.     /// <summary>  
  11.     /// The seconds time out.  
  12.     /// 默认缓存过期时间单位秒  
  13.     /// </summary>  
  14.     private int secondsTimeOut = 24 * 60 * 60;  
  15.   
  16.     /// <summary>  
  17.     /// 给某个键对应的数据设置过期时间  
  18.     /// </summary>  
  19.     /// <param name="key">键</param>  
  20.     /// <param name="seconds">过期时间</param>  
  21.     public void Expire(string key, int seconds) {  
  22.         try {  
  23.             this.redis.Expire(key, seconds);  
  24.         } catch(Exception ex) {  
  25.             var message = string.Format("设置过期时间出错");  
  26.             Logger.Error(message, ex);  
  27.         }  
  28.     }  
  29.   
  30.     /// <summary>  
  31.     /// 释放资源  
  32.     /// </summary>  
  33.     public void Dispose() {  
  34.         if(this.redis != null) {  
  35.             this.redis.Dispose();  
  36.             this.redis = null;  
  37.         }  
  38.   
  39.         GC.Collect();  
  40.     }  
  41.   
  42.     private IEnumerable<string> SplitString(string strSource, string split) {  
  43.         return strSource.Split(split.ToArray());  
  44.     }  
  45.   
  46.     /// <summary>  
  47.     /// 设置单个实体  
  48.     /// </summary>  
  49.     /// <typeparam name="T"></typeparam>  
  50.     /// <param name="key">缓存建</param>  
  51.     /// <param name="t">缓存值</param>  
  52.     /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间:一天</param>  
  53.     public bool Set<T>(string key, T t, int timeout = -1) {  
  54.         try {  
  55.             if(timeout >= 0) {  
  56.                 if(timeout > 0) {  
  57.                     this.secondsTimeOut = timeout;  
  58.                 }  
  59.   
  60.                 var dtTimeOut = DateTime.Now.AddSeconds(this.secondsTimeOut);  
  61.                 return this.redis.Set(key, t, dtTimeOut);  
  62.             }  
  63.   
  64.             return this.redis.Set(key, t);  
  65.         } catch(Exception ex) {  
  66.             string message = string.Format("设置Redis缓存出错");  
  67.             Logger.Error(message, ex);  
  68.         }  
  69.     }  
  70.   
  71.     /// <summary>  
  72.     ///     获取单个实体  
  73.     /// </summary>  
  74.     /// <typeparam name="T">对象类型</typeparam>  
  75.     /// <param name="key">键值</param>  
  76.     public T Get<T>(string key) {  
  77.         try {  
  78.             return this.redis.Get<T>(key);  
  79.         } catch(Exception ex) {  
  80.             string message = string.Format("获取Redis缓存出错");  
  81.             Logger.Error(message, ex);  
  82.         }  
  83.     }  
  84.   
  85.     /// <summary>  
  86.     ///     删除  
  87.     /// </summary>  
  88.     /// <param name="key">键值</param>  
  89.     public bool Remove(string key) {  
  90.         try {  
  91.             return this.redis.Remove(key);  
  92.         } catch(Exception ex) {  
  93.             string message = string.Format("删除Redis缓存出错");  
  94.             Logger.Error(message, ex);  
  95.         }  
  96.     }  
  97.   
  98.     /// <summary>  
  99.     /// 删除所有  
  100.     /// </summary>  
  101.     public void RemoveAll() {  
  102.         var keyList = this.redis.GetAllKeys();  
  103.         this.redis.RemoveAll(keyList);  
  104.     }  
  105.   
  106.     /// <summary>  
  107.     /// 获取Redis的所有key  
  108.     /// </summary>  
  109.     public List<string> ListKey() {  
  110.         return this.redis.GetAllKeys();  
  111.     }  
  112.   
  113.     /// <summary>  
  114.     ///     添加一个对象  
  115.     /// </summary>  
  116.     /// <typeparam name="T">对象类型</typeparam>  
  117.     /// <param name="key">键</param>  
  118.     /// <param name="t"></param>  
  119.     /// <param name="timeout">过期时间(单位为秒) -1:不过期,0:默认过期时间 一天</param>  
  120.     public bool Add<T>(string key, T t, int timeout = -1) {  
  121.         try {  
  122.             if(timeout >= 0) {  
  123.                 if(timeout > 0) {  
  124.                     this.secondsTimeOut = timeout;  
  125.                 }  
  126.   
  127.                 this.redis.Expire(key, this.secondsTimeOut);  
  128.             }  
  129.   
  130.             return this.redis.Add(key, t);  
  131.         } catch(Exception ex) {  
  132.             string message = string.Format("添加Redis缓存出错");  
  133.             Logger.Error(message, ex);  
  134.         }  
  135.     }  
  136.   
  137.     /// <summary>  
  138.     /// 根据IEnumerable数据添加链表  
  139.     /// </summary>  
  140.     /// <typeparam name="T">对象类型</typeparam>  
  141.     /// <param name="key">键</param>  
  142.     /// <param name="values">值</param>  
  143.     /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>  
  144.     public void AddList<T>(string key, IEnumerable<T> values, int timeout = -1) {  
  145.         try {  
  146.             IRedisTypedClient<T> iredisClient = this.redis.As<T>();  
  147.             IRedisList<T> redisList = iredisClient.Lists[key];  
  148.             redisList.AddRange(values);  
  149.             if(timeout > 0) {  
  150.                 if(timeout > 0) {  
  151.                     this.secondsTimeOut = timeout;  
  152.                 }  
  153.   
  154.                 this.redis.Expire(key, this.secondsTimeOut);  
  155.             }  
  156.   
  157.             iredisClient.Save();  
  158.         } catch(Exception ex) {  
  159.             string message = string.Format("添加链表出错");  
  160.             Logger.Error(message, ex);  
  161.         }  
  162.     }  
  163.   
  164.     /// <summary>  
  165.     /// 添加单个实体到链表中  
  166.     /// </summary>  
  167.     /// <typeparam name="T">对象类型</typeparam>  
  168.     /// <param name="key">键</param>  
  169.     /// <param name="Item"></param>  
  170.     /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>  
  171.     public void AddEntityToList<T>(string key, T Item, int timeout = -1) {  
  172.         try {  
  173.             IRedisTypedClient<T> iredisClient = redis.As<T>();  
  174.             IRedisList<T> redisList = iredisClient.Lists[key];  
  175.             redisList.Add(Item);  
  176.             iredisClient.Save();  
  177.             if(timeout >= 0) {  
  178.                 if(timeout > 0) {  
  179.                     this.secondsTimeOut = timeout;  
  180.                 }  
  181.   
  182.                 this.redis.Expire(key, this.secondsTimeOut);  
  183.             }  
  184.         } catch(Exception ex) {  
  185.             string message = string.Format("添加单个的实体到链表中出错");  
  186.             Logger.Error(message, ex);  
  187.         }  
  188.     }  
  189.   
  190.     /// <summary>  
  191.     /// 获取链表  
  192.     /// </summary>  
  193.     /// <typeparam name="T">对象类型</typeparam>  
  194.     /// <param name="key">键</param>  
  195.     public IEnumerable<T> GetList<T>(string key) {  
  196.         try {  
  197.             IRedisTypedClient<T> iredisClient = redis.As<T>();  
  198.             return iredisClient.Lists[key];  
  199.         } catch(Exception ex) {  
  200.             string message = string.Format("获取链表出错");  
  201.             Logger.Error(message, ex);  
  202.         }  
  203.     }  
  204.   
  205.     /// <summary>  
  206.     /// 在链表中删除单个实体  
  207.     /// </summary>  
  208.     /// <typeparam name="T">对象类型</typeparam>  
  209.     /// <param name="key">键</param>  
  210.     public void RemoveEntityFromList<T>(string key, T t) {  
  211.         try {  
  212.             IRedisTypedClient<T> iredisClient = this.redis.As<T>();  
  213.             IRedisList<T> redisList = iredisClient.Lists[key];  
  214.             redisList.RemoveValue(t);  
  215.             iredisClient.Save();  
  216.         } catch(Exception ex) {  
  217.             string message = string.Format("删除链表中的单个实体出错");  
  218.             Logger.Error(message, ex);  
  219.         }  
  220.     }  
  221.   
  222.     /// <summary>  
  223.     /// 根据key移除整个链表  
  224.     /// </summary>  
  225.     /// <param name="key">键</param>  
  226.     public void RemoveAllList<T>(string key) {  
  227.         try {  
  228.             IRedisTypedClient<T> iredisClient = this.redis.As<T>();  
  229.             IRedisList<T> redisList = iredisClient.Lists[key];  
  230.             redisList.RemoveAll();  
  231.             iredisClient.Save();  
  232.         } catch(Exception ex) {  
  233.             string message = string.Format("删除链表集合");  
  234.             Logger.Error(message, ex);  
  235.         }  
  236.     }  
  237. }本文出自GitHub开源网站  
</pre><pre name="code" class="csharp">/// <summary>
/// Redis 帮助类文件
/// </summary>
public class RedisHelper : IDisposable {
    /// <summary>
    /// 针对Log4net的实例
    /// </summary>
    private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
    /// The seconds time out.
    /// 默认缓存过期时间单位秒
    /// </summary>
    private int secondsTimeOut = 24 * 60 * 60;

    /// <summary>
    /// 给某个键对应的数据设置过期时间
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="seconds">过期时间</param>
    public void Expire(string key, int seconds) {
        try {
            this.redis.Expire(key, seconds);
        } catch(Exception ex) {
            var message = string.Format("设置过期时间出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose() {
        if(this.redis != null) {
            this.redis.Dispose();
            this.redis = null;
        }

        GC.Collect();
    }

    private IEnumerable<string> SplitString(string strSource, string split) {
        return strSource.Split(split.ToArray());
    }

    /// <summary>
    /// 设置单个实体
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key">缓存建</param>
    /// <param name="t">缓存值</param>
    /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间:一天</param>
    public bool Set<T>(string key, T t, int timeout = -1) {
        try {
            if(timeout >= 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                var dtTimeOut = DateTime.Now.AddSeconds(this.secondsTimeOut);
                return this.redis.Set(key, t, dtTimeOut);
            }

            return this.redis.Set(key, t);
        } catch(Exception ex) {
            string message = string.Format("设置Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    ///     获取单个实体
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键值</param>
    public T Get<T>(string key) {
        try {
            return this.redis.Get<T>(key);
        } catch(Exception ex) {
            string message = string.Format("获取Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    ///     删除
    /// </summary>
    /// <param name="key">键值</param>
    public bool Remove(string key) {
        try {
            return this.redis.Remove(key);
        } catch(Exception ex) {
            string message = string.Format("删除Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 删除所有
    /// </summary>
    public void RemoveAll() {
        var keyList = this.redis.GetAllKeys();
        this.redis.RemoveAll(keyList);
    }

    /// <summary>
    /// 获取Redis的所有key
    /// </summary>
    public List<string> ListKey() {
        return this.redis.GetAllKeys();
    }

    /// <summary>
    ///     添加一个对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="t"></param>
    /// <param name="timeout">过期时间(单位为秒) -1:不过期,0:默认过期时间 一天</param>
    public bool Add<T>(string key, T t, int timeout = -1) {
        try {
            if(timeout >= 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                this.redis.Expire(key, this.secondsTimeOut);
            }

            return this.redis.Add(key, t);
        } catch(Exception ex) {
            string message = string.Format("添加Redis缓存出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 根据IEnumerable数据添加链表
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="values">值</param>
    /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>
    public void AddList<T>(string key, IEnumerable<T> values, int timeout = -1) {
        try {
            IRedisTypedClient<T> iredisClient = this.redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.AddRange(values);
            if(timeout > 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                this.redis.Expire(key, this.secondsTimeOut);
            }

            iredisClient.Save();
        } catch(Exception ex) {
            string message = string.Format("添加链表出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 添加单个实体到链表中
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="Item"></param>
    /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>
    public void AddEntityToList<T>(string key, T Item, int timeout = -1) {
        try {
            IRedisTypedClient<T> iredisClient = redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.Add(Item);
            iredisClient.Save();
            if(timeout >= 0) {
                if(timeout > 0) {
                    this.secondsTimeOut = timeout;
                }

                this.redis.Expire(key, this.secondsTimeOut);
            }
        } catch(Exception ex) {
            string message = string.Format("添加单个的实体到链表中出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 获取链表
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    public IEnumerable<T> GetList<T>(string key) {
        try {
            IRedisTypedClient<T> iredisClient = redis.As<T>();
            return iredisClient.Lists[key];
        } catch(Exception ex) {
            string message = string.Format("获取链表出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 在链表中删除单个实体
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="key">键</param>
    public void RemoveEntityFromList<T>(string key, T t) {
        try {
            IRedisTypedClient<T> iredisClient = this.redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.RemoveValue(t);
            iredisClient.Save();
        } catch(Exception ex) {
            string message = string.Format("删除链表中的单个实体出错");
            Logger.Error(message, ex);
        }
    }

    /// <summary>
    /// 根据key移除整个链表
    /// </summary>
    /// <param name="key">键</param>
    public void RemoveAllList<T>(string key) {
        try {
            IRedisTypedClient<T> iredisClient = this.redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[key];
            redisList.RemoveAll();
            iredisClient.Save();
        } catch(Exception ex) {
            string message = string.Format("删除链表集合");
            Logger.Error(message, ex);
        }
    }
}本文出自GitHub开源网站


=================================

asp.net mvc 用Redis实现分布式集群共享Session

1、这两天研究Redis搞分布式session问题,网上找的资料都是用ServiceStack.Redis来实现的,但是在做性能测试的时候 发现最新的v4版本有限制每小时候最多请求6000次,因为官网开始商业化要收费了,好坑爹的说,还好我前期弄了个性能测试列子,不然上线以后出问题那就 麻烦了。后面找了个NServiceKit.Redis(好像就是ServiceStack.Redis的v3版本)来替代v4的收费版。

2、解决方案是 Redis+cookie方式实现记录用户登录状态

     cookie:存放用户的ID,这个ID是经过加密的,并且后台可以通过密钥解密。

     Redis:key/value 方式存储,key存放比如:user_1。  value存放用户实体对象。

3、先安装一个Redis,windows的版本在本地进行测试,后期上线更换linux系统的Redis替换一下ip就可以了。

4、添加一个Session管理类


  1. public class SessionHelper  
  2.     {  
  3.         private const int secondsTimeOut = 60 * 20;  //默认过期时间20分钟  单位秒  
  4.   
  5.   
  6.         public RedisHelper Redis = new RedisHelper(false);  
  7.         public LoginUserInfo this[string key]  
  8.         {  
  9.             get  
  10.             {  
  11.                 string webCookie = WebHelper.GetCookie(key);  
  12.                 if (webCookie == "")  
  13.                 {  
  14.                     return null;  
  15.                 }  
  16.                 key = key + "_" + SecureHelper.AESDecrypt(webCookie);  
  17.   
  18.                 //距离过期时间还有多少秒  
  19.                 long l = Redis.TTL(key);  
  20.                 if (l >= 0)  
  21.                 {  
  22.                     Redis.Expire(key, secondsTimeOut);  
  23.                 }  
  24.                   
  25.                 return Redis.Get<LoginUserInfo>(key);  
  26.             }  
  27.             set  
  28.             {  
  29.                 SetSession(key, value);  
  30.             }  
  31.         }  
  32.         public void SetSession(string key, LoginUserInfo value)  
  33.         {  
  34.             if (string.IsNullOrWhiteSpace(key))  
  35.             {  
  36.                 throw new Exception("Key is Null or Epmty");  
  37.             }  
  38.             WebHelper.SetCookie(key, SecureHelper.AESEncrypt(value.ID.ToString()));  
  39.             key = key + "_" + value.ID;  
  40.             Redis.Set<LoginUserInfo>(key, value, secondsTimeOut);  
  41.         }  
  42.   
  43.         /// <summary>  
  44.         /// 移除Session  
  45.         /// </summary>  
  46.         /// <param name="key"></param>  
  47.         /// <returns></returns>  
  48.         public bool Remove(string key)  
  49.         {  
  50.             var rs = Redis.Remove(key + "_" + SecureHelper.AESDecrypt(WebHelper.GetCookie(key)));  
  51.             WebHelper.DeleteCookie(key);  
  52.             return rs;  
  53.         }  
  54.                
  55.     }  
  56.   
  57. SessionHelper  
public class SessionHelper
    {
        private const int secondsTimeOut = 60 * 20;  //默认过期时间20分钟  单位秒


        public RedisHelper Redis = new RedisHelper(false);
        public LoginUserInfo this[string key]
        {
            get
            {
                string webCookie = WebHelper.GetCookie(key);
                if (webCookie == "")
                {
                    return null;
                }
                key = key + "_" + SecureHelper.AESDecrypt(webCookie);

                //距离过期时间还有多少秒
                long l = Redis.TTL(key);
                if (l >= 0)
                {
                    Redis.Expire(key, secondsTimeOut);
                }
                
                return Redis.Get<LoginUserInfo>(key);
            }
            set
            {
                SetSession(key, value);
            }
        }
        public void SetSession(string key, LoginUserInfo value)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new Exception("Key is Null or Epmty");
            }
            WebHelper.SetCookie(key, SecureHelper.AESEncrypt(value.ID.ToString()));
            key = key + "_" + value.ID;
            Redis.Set<LoginUserInfo>(key, value, secondsTimeOut);
        }

        /// <summary>
        /// 移除Session
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            var rs = Redis.Remove(key + "_" + SecureHelper.AESDecrypt(WebHelper.GetCookie(key)));
            WebHelper.DeleteCookie(key);
            return rs;
        }
             
    }

SessionHelper
5、Redis操作类
  1. public class RedisHelper : IDisposable  
  2.     {  
  3.        private RedisClient Redis = new RedisClient("127.0.0.1", 6379);  
  4.         //缓存池  
  5.         PooledRedisClientManager prcm = new PooledRedisClientManager();  
  6.   
  7.         //默认缓存过期时间单位秒  
  8.         public int secondsTimeOut = 20 * 60;  
  9.   
  10.         /// <summary>  
  11.         /// 缓冲池  
  12.         /// </summary>  
  13.         /// <param name="readWriteHosts"></param>  
  14.         /// <param name="readOnlyHosts"></param>  
  15.         /// <returns></returns>  
  16.         public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)  
  17.         {  
  18.             return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,  
  19.                 new RedisClientManagerConfig  
  20.                 {  
  21.                     MaxWritePoolSize = readWriteHosts.Length * 5,  
  22.                     MaxReadPoolSize = readOnlyHosts.Length * 5,  
  23.                     AutoStart = true,  
  24.                 });   
  25.         }  
  26.         /// <summary>  
  27.         /// 构造函数  
  28.         /// </summary>  
  29.         /// <param name="OpenPooledRedis">是否开启缓冲池</param>  
  30.         public RedisHelper(bool OpenPooledRedis = false)  
  31.         {  
  32.   
  33.             if (OpenPooledRedis)  
  34.             {  
  35.                 prcm = CreateManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" });  
  36.                 Redis = prcm.GetClient() as RedisClient;  
  37.             }  
  38.         }  
  39.         /// <summary>  
  40.         /// 距离过期时间还有多少秒  
  41.         /// </summary>  
  42.         /// <param name="key"></param>  
  43.         /// <returns></returns>  
  44.         public long TTL(string key)  
  45.         {  
  46.             return Redis.Ttl(key);  
  47.         }  
  48.         /// <summary>  
  49.         /// 设置过期时间  
  50.         /// </summary>  
  51.         /// <param name="key"></param>  
  52.         /// <param name="timeout"></param>  
  53.         public void Expire(string key,int timeout = 0)  
  54.         {  
  55.             if (timeout >= 0)  
  56.             {  
  57.                 if (timeout > 0)  
  58.                 {  
  59.                     secondsTimeOut = timeout;  
  60.                 }  
  61.                 Redis.Expire(key, secondsTimeOut);  
  62.             }  
  63.         }  
  64.  
  65.         #region Key/Value存储  
  66.         /// <summary>  
  67.         /// 设置缓存  
  68.         /// </summary>  
  69.         /// <typeparam name="T"></typeparam>  
  70.         /// <param name="key">缓存建</param>  
  71.         /// <param name="t">缓存值</param>  
  72.         /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间</param>  
  73.         /// <returns></returns>  
  74.         public bool Set<T>(string key, T t, int timeout = 0)  
  75.         {  
  76.             Redis.Set<T>(key, t);  
  77.             if (timeout >= 0)  
  78.             {  
  79.                 if (timeout > 0)  
  80.                 {  
  81.                     secondsTimeOut = timeout;  
  82.                 }  
  83.                 Redis.Expire(key, secondsTimeOut);  
  84.             }  
  85.             return true;  
  86.               
  87.         }  
  88.         /// <summary>  
  89.         /// 获取  
  90.         /// </summary>  
  91.         /// <typeparam name="T"></typeparam>  
  92.         /// <param name="key"></param>  
  93.         /// <returns></returns>  
  94.         public T Get<T>(string key)  
  95.         {  
  96.             return Redis.Get<T>(key);  
  97.         }  
  98.         /// <summary>  
  99.         /// 删除  
  100.         /// </summary>  
  101.         /// <param name="key"></param>  
  102.         /// <returns></returns>  
  103.         public bool Remove(string key)  
  104.         {  
  105.             return Redis.Remove(key);  
  106.         }  
  107.         #endregion  
  108.   
  109.         //释放资源  
  110.         public void Dispose()  
  111.         {  
  112.             if (Redis != null)  
  113.             {  
  114.                 Redis.Dispose();  
  115.                 Redis = null;  
  116.             }  
  117.             GC.Collect();  
  118.   
  119.         }  
  120.     }  
  121.   
  122. RedisHelper  
public class RedisHelper : IDisposable
    {
       private RedisClient Redis = new RedisClient("127.0.0.1", 6379);
        //缓存池
        PooledRedisClientManager prcm = new PooledRedisClientManager();

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

        /// <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,
                }); 
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="OpenPooledRedis">是否开启缓冲池</param>
        public RedisHelper(bool OpenPooledRedis = false)
        {

            if (OpenPooledRedis)
            {
                prcm = CreateManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" });
                Redis = prcm.GetClient() as RedisClient;
            }
        }
        /// <summary>
        /// 距离过期时间还有多少秒
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public long TTL(string key)
        {
            return Redis.Ttl(key);
        }
        /// <summary>
        /// 设置过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="timeout"></param>
        public void Expire(string key,int timeout = 0)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
        }

        #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)
        {
            Redis.Set<T>(key, t);
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
            return true;
            
        }
        /// <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);
        }
        #endregion

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

        }
    }

RedisHelper

用C#封装的ServiceStack.redis操作类

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ServiceStack.Redis;  
  7. namespace TestRedis  
  8. {  
  9.     class RedisHelper:IDisposable  
  10.     {  
  11.         /*copyright@2013 All Rights Reserved 
  12.          * Author:Mars 
  13.          * Date:2013.08.27 
  14.          * QQ:258248340 
  15.          * servicestack.redis为github中的开源项目 
  16.          * redis是一个典型的k/v型数据库 
  17.          * redis共支持五种类型的数据 string,list,hash,set,sortedset 
  18.          *  
  19.          * string是最简单的字符串类型 
  20.          *  
  21.          * list是字符串列表,其内部是用双向链表实现的,因此在获取/设置数据时可以支持正负索引 
  22.          * 也可以将其当做堆栈结构使用 
  23.          *  
  24.          * hash类型是一种字典结构,也是最接近RDBMS的数据类型,其存储了字段和字段值的映射,但字段值只能是 
  25.          * 字符串类型,散列类型适合存储对象,建议使用对象类别和ID构成键名,使用字段表示对象属性,字 
  26.          * 段值存储属性值,例如:car:2 price 500 ,car:2  color black,用redis命令设置散列时,命令格式 
  27.          * 如下:HSET key field value,即key,字段名,字段值 
  28.          *  
  29.          * set是一种集合类型,redis中可以对集合进行交集,并集和互斥运算 
  30.          *            
  31.          * sorted set是在集合的基础上为每个元素关联了一个“分数”,我们能够 
  32.          * 获得分数最高的前N个元素,获得指定分数范围内的元素,元素是不同的,但是"分数"可以是相同的 
  33.          * set是用散列表和跳跃表实现的,获取数据的速度平均为o(log(N)) 
  34.          *  
  35.          * 需要注意的是,redis所有数据类型都不支持嵌套 
  36.          * redis中一般不区分插入和更新操作,只是命令的返回值不同 
  37.          * 在插入key时,如果不存在,将会自动创建 
  38.          *  
  39.          * 在实际生产环境中,由于多线程并发的关系,建议使用连接池,本类只是用于测试简单的数据类型 
  40.          */  
  41.   
  42.         /* 
  43.          * 以下方法为基本的设置数据和取数据 
  44.          */  
  45.         private static RedisClient redisCli = null;  
  46.         /// <summary>  
  47.         /// 建立redis长连接  
  48.         /// </summary>  
  49.         /// 将此处的IP换为自己的redis实例IP,如果设有密码,第三个参数为密码,string 类型  
  50.         public static void CreateClient(string hostIP,int port,string keyword)  
  51.         {  
  52.             if (redisCli == null)  
  53.             {  
  54.                 redisCli = new RedisClient(hostIP, port, keyword);  
  55.             }  
  56.    
  57.         }  
  58.         public static void CreateClient(string hostIP, int port)  
  59.         {  
  60.             if (redisCli == null)  
  61.             {  
  62.                 redisCli = new RedisClient(hostIP, port);  
  63.              }  
  64.    
  65.         }  
  66.         //private static RedisClient redisCli = new RedisClient("192.168.101.165", 6379, "123456");  
  67.         /// <summary>  
  68.         /// 获取key,返回string格式  
  69.         /// </summary>  
  70.         /// <param name="key"></param>  
  71.         /// <returns></returns>  
  72.         public static string getValueString(string key)  
  73.         {  
  74.           
  75.                 string value = redisCli.GetValue(key);  
  76.                 return value;  
  77.              
  78.             
  79.         }  
  80.         /// <summary>  
  81.         /// 获取key,返回byte[]格式  
  82.         /// </summary>  
  83.         /// <param name="key"></param>  
  84.         /// <returns></returns>  
  85.         public static byte[] getValueByte(string key)  
  86.         {  
  87.             byte[] value = redisCli.Get(key);  
  88.             return value;  
  89.         }  
  90.         /// <summary>  
  91.         /// 获得某个hash型key下的所有字段  
  92.         /// </summary>  
  93.         /// <param name="hashId"></param>  
  94.         /// <returns></returns>  
  95.         public static List<string> GetHashFields(string hashId)  
  96.         {  
  97.             List<string> hashFields = redisCli.GetHashKeys(hashId);  
  98.             return hashFields;  
  99.         }  
  100.         /// <summary>  
  101.         /// 获得某个hash型key下的所有值  
  102.         /// </summary>  
  103.         /// <param name="hashId"></param>  
  104.         /// <returns></returns>  
  105.         public static List<string> GetHashValues(string hashId)  
  106.         {  
  107.             List<string> hashValues = redisCli.GetHashKeys(hashId);  
  108.             return hashValues;  
  109.         }  
  110.         /// <summary>  
  111.         /// 获得hash型key某个字段的值  
  112.         /// </summary>  
  113.         /// <param name="key"></param>  
  114.         /// <param name="field"></param>  
  115.         public static string GetHashField(string key, string field)  
  116.         {  
  117.             string value = redisCli.GetValueFromHash(key, field);  
  118.             return value;  
  119.         }  
  120.         /// <summary>  
  121.         /// 设置hash型key某个字段的值  
  122.         /// </summary>  
  123.         /// <param name="key"></param>  
  124.         /// <param name="field"></param>  
  125.         /// <param name="value"></param>  
  126.         public static void SetHashField(string key, string field, string value)  
  127.         {  
  128.             redisCli.SetEntryInHash(key, field, value);  
  129.         }  
  130.         /// <summary>  
  131.         ///使某个字段增加  
  132.         /// </summary>  
  133.         /// <param name="key"></param>  
  134.         /// <param name="field"></param>  
  135.         /// <returns></returns>  
  136.         public static void SetHashIncr(string key, string field, long incre)  
  137.         {  
  138.             redisCli.IncrementValueInHash(key, field, incre);  
  139.   
  140.         }  
  141.         /// <summary>  
  142.         /// 向list类型数据添加成员,向列表底部(右侧)添加  
  143.         /// </summary>  
  144.         /// <param name="Item"></param>  
  145.         /// <param name="list"></param>  
  146.         public static void AddItemToListRight(string list, string item)  
  147.         {  
  148.             redisCli.AddItemToList(list, item);  
  149.         }  
  150.         /// <summary>  
  151.         /// 向list类型数据添加成员,向列表顶部(左侧)添加  
  152.         /// </summary>  
  153.         /// <param name="list"></param>  
  154.         /// <param name="item"></param>  
  155.         public static void AddItemToListLeft(string list, string item)  
  156.         {  
  157.             redisCli.LPush(list, Encoding.Default.GetBytes(item));  
  158.         }  
  159.         /// <summary>  
  160.         /// 从list类型数据读取所有成员  
  161.         /// </summary>  
  162.         public static List<string> GetAllItems(string list)  
  163.         {  
  164.             List<string> listMembers = redisCli.GetAllItemsFromList(list);  
  165.             return listMembers;  
  166.         }  
  167.         /// <summary>  
  168.         /// 从list类型数据指定索引处获取数据,支持正索引和负索引  
  169.         /// </summary>  
  170.         /// <param name="list"></param>  
  171.         /// <returns></returns>  
  172.         public static string GetItemFromList(string list, int index)  
  173.         {  
  174.             string item = redisCli.GetItemFromList(list, index);  
  175.             return item;  
  176.         }  
  177.         /// <summary>  
  178.         /// 向列表底部(右侧)批量添加数据  
  179.         /// </summary>  
  180.         /// <param name="list"></param>  
  181.         /// <param name="values"></param>  
  182.         public static void GetRangeToList(string list, List<string> values)  
  183.         {  
  184.             redisCli.AddRangeToList(list, values);  
  185.         }  
  186.         /// <summary>  
  187.         /// 向集合中添加数据  
  188.         /// </summary>  
  189.         /// <param name="item"></param>  
  190.         /// <param name="set"></param>  
  191.         public static void GetItemToSet(string item, string set)  
  192.         {  
  193.             redisCli.AddItemToSet(item, set);  
  194.         }  
  195.         /// <summary>  
  196.         /// 获得集合中所有数据  
  197.         /// </summary>  
  198.         /// <param name="set"></param>  
  199.         /// <returns></returns>  
  200.         public static HashSet<string> GetAllItemsFromSet(string set)  
  201.         {  
  202.             HashSet<string> items = redisCli.GetAllItemsFromSet(set);  
  203.             return items;  
  204.         }  
  205.         /// <summary>  
  206.         /// 获取fromSet集合和其他集合不同的数据  
  207.         /// </summary>  
  208.         /// <param name="fromSet"></param>  
  209.         /// <param name="toSet"></param>  
  210.         /// <returns></returns>  
  211.         public static HashSet<string> GetSetDiff(string fromSet, params string[] toSet)  
  212.         {  
  213.             HashSet<string> diff = redisCli.GetDifferencesFromSet(fromSet, toSet);  
  214.             return diff;  
  215.         }  
  216.         /// <summary>  
  217.         /// 获得所有集合的并集  
  218.         /// </summary>  
  219.         /// <param name="set"></param>  
  220.         /// <returns></returns>  
  221.         public static HashSet<string> GetSetUnion(params string[] set)  
  222.         {  
  223.             HashSet<string> union = redisCli.GetUnionFromSets(set);  
  224.             return union;  
  225.         }  
  226.         /// <summary>  
  227.         /// 获得所有集合的交集  
  228.         /// </summary>  
  229.         /// <param name="set"></param>  
  230.         /// <returns></returns>  
  231.         public static HashSet<string> GetSetInter(params string[] set)  
  232.         {  
  233.             HashSet<string> inter = redisCli.GetIntersectFromSets(set);  
  234.             return inter;  
  235.         }  
  236.         /// <summary>  
  237.         /// 向有序集合中添加元素  
  238.         /// </summary>  
  239.         /// <param name="set"></param>  
  240.         /// <param name="value"></param>  
  241.         /// <param name="score"></param>  
  242.         public static void AddItemToSortedSet(string set,string value,long score)  
  243.         {  
  244.             redisCli.AddItemToSortedSet(set,value,score);  
  245.         }  
  246.         /// <summary>  
  247.         /// 获得某个值在有序集合中的排名,按分数的降序排列  
  248.         /// </summary>  
  249.         /// <param name="set"></param>  
  250.         /// <param name="value"></param>  
  251.         /// <returns></returns>  
  252.         public static int GetItemIndexInSortedSetDesc(string setstring value)  
  253.         {  
  254.             int index = redisCli.GetItemIndexInSortedSetDesc(set, value);  
  255.             return index;  
  256.         }  
  257.         /// <summary>  
  258.         /// 获得某个值在有序集合中的排名,按分数的升序排列  
  259.         /// </summary>  
  260.         /// <param name="set"></param>  
  261.         /// <param name="value"></param>  
  262.         /// <returns></returns>  
  263.         public static int GetItemIndexInSortedSet(string setstring value)  
  264.         {  
  265.             int index = redisCli.GetItemIndexInSortedSet(set, value);  
  266.             return index;  
  267.         }  
  268.         /// <summary>  
  269.         /// 获得有序集合中某个值得分数  
  270.         /// </summary>  
  271.         /// <param name="set"></param>  
  272.         /// <param name="value"></param>  
  273.         /// <returns></returns>  
  274.         public static double GetItemScoreInSortedSet(string setstring value)  
  275.         {  
  276.             double score = redisCli.GetItemScoreInSortedSet(set, value);  
  277.             return score;  
  278.         }  
  279.         /// <summary>  
  280.         /// 获得有序集合中,某个排名范围的所有值  
  281.         /// </summary>  
  282.         /// <param name="set"></param>  
  283.         /// <param name="beginRank"></param>  
  284.         /// <param name="endRank"></param>  
  285.         /// <returns></returns>  
  286.         public static List<string> GetRangeFromSortedSet(string set,int beginRank, int endRank)  
  287.         {  
  288.             List<string> valueList=redisCli.GetRangeFromSortedSet(set,beginRank,endRank);  
  289.             return valueList;  
  290.         }  
  291.         /// <summary>  
  292.         /// 获得有序集合中,某个分数范围内的所有值,升序  
  293.         /// </summary>  
  294.         /// <param name="set"></param>  
  295.         /// <param name="beginScore"></param>  
  296.         /// <param name="endScore"></param>  
  297.         /// <returns></returns>  
  298.         public static List<string> GetRangeFromSortedSet(string setdouble beginScore, double endScore)  
  299.         {  
  300.             List<string> valueList = redisCli.GetRangeFromSortedSetByHighestScore(set, beginScore, endScore);  
  301.             return valueList;  
  302.         }  
  303.         /// <summary>  
  304.         /// 获得有序集合中,某个分数范围内的所有值,降序  
  305.         /// </summary>  
  306.         /// <param name="set"></param>  
  307.         /// <param name="beginScore"></param>  
  308.         /// <param name="endScore"></param>  
  309.         /// <returns></returns>  
  310.         public static List<string> GetRangeFromSortedSetDesc(string setdouble beginScore, double endScore)  
  311.         {  
  312.             List<string> vlaueList=redisCli.GetRangeFromSortedSetByLowestScore(set,beginScore,endScore);  
  313.             return vlaueList;  
  314.         }  
  315.         public void Dispose()  
  316.         {  
  317.             redisCli.Dispose();  
  318.         }  
  319.    
  320.     }  
  321. }  
  322.   
  323. RedisHelper  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;
namespace TestRedis
{
    class RedisHelper:IDisposable
    {
        /*copyright@2013 All Rights Reserved
         * Author:Mars
         * Date:2013.08.27
         * QQ:258248340
         * servicestack.redis为github中的开源项目
         * redis是一个典型的k/v型数据库
         * redis共支持五种类型的数据 string,list,hash,set,sortedset
         * 
         * string是最简单的字符串类型
         * 
         * list是字符串列表,其内部是用双向链表实现的,因此在获取/设置数据时可以支持正负索引
         * 也可以将其当做堆栈结构使用
         * 
         * hash类型是一种字典结构,也是最接近RDBMS的数据类型,其存储了字段和字段值的映射,但字段值只能是
         * 字符串类型,散列类型适合存储对象,建议使用对象类别和ID构成键名,使用字段表示对象属性,字
         * 段值存储属性值,例如:car:2 price 500 ,car:2  color black,用redis命令设置散列时,命令格式
         * 如下:HSET key field value,即key,字段名,字段值
         * 
         * set是一种集合类型,redis中可以对集合进行交集,并集和互斥运算
         *           
         * sorted set是在集合的基础上为每个元素关联了一个“分数”,我们能够
         * 获得分数最高的前N个元素,获得指定分数范围内的元素,元素是不同的,但是"分数"可以是相同的
         * set是用散列表和跳跃表实现的,获取数据的速度平均为o(log(N))
         * 
         * 需要注意的是,redis所有数据类型都不支持嵌套
         * redis中一般不区分插入和更新操作,只是命令的返回值不同
         * 在插入key时,如果不存在,将会自动创建
         * 
         * 在实际生产环境中,由于多线程并发的关系,建议使用连接池,本类只是用于测试简单的数据类型
         */

        /*
         * 以下方法为基本的设置数据和取数据
         */
        private static RedisClient redisCli = null;
        /// <summary>
        /// 建立redis长连接
        /// </summary>
        /// 将此处的IP换为自己的redis实例IP,如果设有密码,第三个参数为密码,string 类型
        public static void CreateClient(string hostIP,int port,string keyword)
        {
            if (redisCli == null)
            {
                redisCli = new RedisClient(hostIP, port, keyword);
            }
 
        }
        public static void CreateClient(string hostIP, int port)
        {
            if (redisCli == null)
            {
                redisCli = new RedisClient(hostIP, port);
             }
 
        }
        //private static RedisClient redisCli = new RedisClient("192.168.101.165", 6379, "123456");
        /// <summary>
        /// 获取key,返回string格式
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string getValueString(string key)
        {
        
                string value = redisCli.GetValue(key);
                return value;
           
          
        }
        /// <summary>
        /// 获取key,返回byte[]格式
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] getValueByte(string key)
        {
            byte[] value = redisCli.Get(key);
            return value;
        }
        /// <summary>
        /// 获得某个hash型key下的所有字段
        /// </summary>
        /// <param name="hashId"></param>
        /// <returns></returns>
        public static List<string> GetHashFields(string hashId)
        {
            List<string> hashFields = redisCli.GetHashKeys(hashId);
            return hashFields;
        }
        /// <summary>
        /// 获得某个hash型key下的所有值
        /// </summary>
        /// <param name="hashId"></param>
        /// <returns></returns>
        public static List<string> GetHashValues(string hashId)
        {
            List<string> hashValues = redisCli.GetHashKeys(hashId);
            return hashValues;
        }
        /// <summary>
        /// 获得hash型key某个字段的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="field"></param>
        public static string GetHashField(string key, string field)
        {
            string value = redisCli.GetValueFromHash(key, field);
            return value;
        }
        /// <summary>
        /// 设置hash型key某个字段的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        public static void SetHashField(string key, string field, string value)
        {
            redisCli.SetEntryInHash(key, field, value);
        }
        /// <summary>
        ///使某个字段增加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static void SetHashIncr(string key, string field, long incre)
        {
            redisCli.IncrementValueInHash(key, field, incre);

        }
        /// <summary>
        /// 向list类型数据添加成员,向列表底部(右侧)添加
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="list"></param>
        public static void AddItemToListRight(string list, string item)
        {
            redisCli.AddItemToList(list, item);
        }
        /// <summary>
        /// 向list类型数据添加成员,向列表顶部(左侧)添加
        /// </summary>
        /// <param name="list"></param>
        /// <param name="item"></param>
        public static void AddItemToListLeft(string list, string item)
        {
            redisCli.LPush(list, Encoding.Default.GetBytes(item));
        }
        /// <summary>
        /// 从list类型数据读取所有成员
        /// </summary>
        public static List<string> GetAllItems(string list)
        {
            List<string> listMembers = redisCli.GetAllItemsFromList(list);
            return listMembers;
        }
        /// <summary>
        /// 从list类型数据指定索引处获取数据,支持正索引和负索引
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetItemFromList(string list, int index)
        {
            string item = redisCli.GetItemFromList(list, index);
            return item;
        }
        /// <summary>
        /// 向列表底部(右侧)批量添加数据
        /// </summary>
        /// <param name="list"></param>
        /// <param name="values"></param>
        public static void GetRangeToList(string list, List<string> values)
        {
            redisCli.AddRangeToList(list, values);
        }
        /// <summary>
        /// 向集合中添加数据
        /// </summary>
        /// <param name="item"></param>
        /// <param name="set"></param>
        public static void GetItemToSet(string item, string set)
        {
            redisCli.AddItemToSet(item, set);
        }
        /// <summary>
        /// 获得集合中所有数据
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static HashSet<string> GetAllItemsFromSet(string set)
        {
            HashSet<string> items = redisCli.GetAllItemsFromSet(set);
            return items;
        }
        /// <summary>
        /// 获取fromSet集合和其他集合不同的数据
        /// </summary>
        /// <param name="fromSet"></param>
        /// <param name="toSet"></param>
        /// <returns></returns>
        public static HashSet<string> GetSetDiff(string fromSet, params string[] toSet)
        {
            HashSet<string> diff = redisCli.GetDifferencesFromSet(fromSet, toSet);
            return diff;
        }
        /// <summary>
        /// 获得所有集合的并集
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static HashSet<string> GetSetUnion(params string[] set)
        {
            HashSet<string> union = redisCli.GetUnionFromSets(set);
            return union;
        }
        /// <summary>
        /// 获得所有集合的交集
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static HashSet<string> GetSetInter(params string[] set)
        {
            HashSet<string> inter = redisCli.GetIntersectFromSets(set);
            return inter;
        }
        /// <summary>
        /// 向有序集合中添加元素
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <param name="score"></param>
        public static void AddItemToSortedSet(string set,string value,long score)
        {
            redisCli.AddItemToSortedSet(set,value,score);
        }
        /// <summary>
        /// 获得某个值在有序集合中的排名,按分数的降序排列
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int GetItemIndexInSortedSetDesc(string set, string value)
        {
            int index = redisCli.GetItemIndexInSortedSetDesc(set, value);
            return index;
        }
        /// <summary>
        /// 获得某个值在有序集合中的排名,按分数的升序排列
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int GetItemIndexInSortedSet(string set, string value)
        {
            int index = redisCli.GetItemIndexInSortedSet(set, value);
            return index;
        }
        /// <summary>
        /// 获得有序集合中某个值得分数
        /// </summary>
        /// <param name="set"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static double GetItemScoreInSortedSet(string set, string value)
        {
            double score = redisCli.GetItemScoreInSortedSet(set, value);
            return score;
        }
        /// <summary>
        /// 获得有序集合中,某个排名范围的所有值
        /// </summary>
        /// <param name="set"></param>
        /// <param name="beginRank"></param>
        /// <param name="endRank"></param>
        /// <returns></returns>
        public static List<string> GetRangeFromSortedSet(string set,int beginRank, int endRank)
        {
            List<string> valueList=redisCli.GetRangeFromSortedSet(set,beginRank,endRank);
            return valueList;
        }
        /// <summary>
        /// 获得有序集合中,某个分数范围内的所有值,升序
        /// </summary>
        /// <param name="set"></param>
        /// <param name="beginScore"></param>
        /// <param name="endScore"></param>
        /// <returns></returns>
        public static List<string> GetRangeFromSortedSet(string set, double beginScore, double endScore)
        {
            List<string> valueList = redisCli.GetRangeFromSortedSetByHighestScore(set, beginScore, endScore);
            return valueList;
        }
        /// <summary>
        /// 获得有序集合中,某个分数范围内的所有值,降序
        /// </summary>
        /// <param name="set"></param>
        /// <param name="beginScore"></param>
        /// <param name="endScore"></param>
        /// <returns></returns>
        public static List<string> GetRangeFromSortedSetDesc(string set, double beginScore, double endScore)
        {
            List<string> vlaueList=redisCli.GetRangeFromSortedSetByLowestScore(set,beginScore,endScore);
            return vlaueList;
        }
        public void Dispose()
        {
            redisCli.Dispose();
        }
 
    }
}

RedisHelper

==========================================

Redis主从服务部署

Redis服务器及应用

基于Redis缓存的Session共享(附源码)

基于redis实现分布式Session

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值