String字符串类型数据操作封装,String字符串类型数据操作封装

本文版权归乐乎和小编本人共同全数,转发和爬虫请申明原文链接
http://www.cnblogs.com/tdws/tag/NoSql/

本文版权归乐乎和小编本人共同拥有,转发和爬虫请注解原文链接
http://www.cnblogs.com/tdws/tag/NoSql/

目录

目录

一、基本功配置封装

一、基础配置封装

二、String字符串类型数据操作封装

二、String字符串类型数据操作封装

三、Hash散列类型数据操作封装

三、Hash散列类型数据操作封装

四 、List列表类型数据操作封装(建议活动封装)

四 、List列表类型数据操作封装(建议活动封装)

五 、Set集合类型数据操作封装(提议活动封装)

伍 、Set集合类型数据操作封装(建议活动封装)

陆 、Sort Set集合数据类型操作封装(建议活动封装)

六 、Sort Set集合数据类型操作封装(提议活动封装)

七、公告订阅(Pub/Sub)格局在StackExchange.Redis中的使用

七、表露订阅(Pub/Sub)方式在StackExchange.Redis中的使用

⑧ 、主从配置,哨兵相关计划

捌 、主从配置,哨兵相关安顿

② 、String字符串类型数据操作封装

② 、String字符串类型数据操作封装

上面那段画假设看二遍没看懂,请看过代码后再度来读书:

上边那段画纵然看一遍没看懂,请看过代码后再一次来阅读:

大家有必不可少先提到ConnectionMultiplexer类,它是StackExchange提必要大家的1个类,它将多服务器的详细音信隐藏,因为那几个类为大家做了无数工作,它的统一筹划指标是为了在调用者间共享和选定。你绝不每回操作都创设那样3个ConnectionMultiplexer,它是全然线程安全的。它兼具ConnectionMultiplexer.Connect和onnectionMultiplexer.ConnectAsync来链接Redis。链接
参数是二个字符串或然二个ConfigurationOptions对象。其一类完毕了IDisposable接口,你能够在您不要求的时候释放对象,通过using或许dispose。然则你不用平时来刑释它,因为大家要时不时复用。你有二种供给时,要求选拔ConnectionMultiplexer,链接Redis,发表订阅情势,访问2个单独的服务器大概监察的目标。除了宗旨使用,更加多的请看github文书档案,https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md

咱俩有必不可少先提到ConnectionMultiplexer类,它是StackExchange提须要我们的2个类,它将多服务器的详细音信隐藏,因为这么些类为我们做了重重工作,它的宏图目的是为着在调用者间共享和选定。你绝不每一遍操作都成立那样一个ConnectionMultiplexer,它是完全线程安全的。它装有ConnectionMultiplexer.Connect和onnectionMultiplexer.ConnectAsync来链接Redis。链接
参数是一个字符串或许三个ConfigurationOptions对象。本条类完结了IDisposable接口,你能够在你不要求的时候释放对象,通过using只怕dispose。不过你不用平日来刑释它,因为我们要平时复用。你有二种要求时,必要使用ConnectionMultiplexer,链接Redis,公布订阅情势,访问1个独门的服务器或然监察的目标。除了主导使用,更加多的请看github文书档案,https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md

我们在IRedisClient中定义如下String数据类型方法:

咱俩在IRedisClient中定义如下String数据类型方法:

假如你觉得代码太多,当VS按下神速键ctrl+M+O吧

假若您觉得代码太多,当VS按下急忙键ctrl+M+O吧

  1 #region 程序集 RedisRepository, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  2 // Author:吴双  2016.8.28   联系邮箱 wscoder@outlook.com
  3 #endregion
  4 using System;
  5 using System.Collections.Generic;
  6 using StackExchange.Redis;
  7 
  8 namespace RedisRepository
  9 {
 10     public interface IRedisClient
 11     {
 12         #region Redis String类型操作
 13         /// <summary>
 14         /// Redis String类型 新增一条记录
 15         /// </summary>
 16         /// <typeparam name="T">generic refrence type</typeparam>
 17         /// <param name="key">unique key of value</param>
 18         /// <param name="value">value of key of type object</param>
 19         /// <param name="expiresAt">time span of expiration</param>
 20         /// <param name= "when">枚举类型</param>
 21         /// <param name="commandFlags"></param>
 22         /// <returns>true or false</returns>
 23         bool StringSet<T>(string key, object value, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class;
 24 
 25         /// <summary>
 26         /// Redis String类型 新增一条记录
 27         /// </summary>
 28         /// <typeparam name="T">generic refrence type</typeparam>
 29         /// <param name="key">unique key of value</param>
 30         /// <param name="value">value of key of type object</param>
 31         /// <param name="expiresAt">time span of expiration</param>
 32         /// <param name= "when">枚举类型</param>
 33         /// <param name="commandFlags"></param>
 34         /// <returns>true or false</returns>
 35         bool StringSet<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class;
 36 
 37         /// <summary>
 38         /// 更新时应使用此方法,代码更可读。
 39         /// </summary>
 40         /// <typeparam name="T"></typeparam>
 41         /// <param name="key"></param>
 42         /// <param name="value"></param>
 43         /// <param name="expiresAt"></param>
 44         /// <param name="when"></param>
 45         /// <param name="commandFlags"></param>
 46         /// <returns></returns>
 47         bool StringUpdate<T>(string key, T value, TimeSpan expiresAt, When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class;
 48 
 49         /// <summary>
 50         /// Redis String类型  Get
 51         /// </summary>
 52         /// <typeparam name="T"></typeparam>
 53         /// <param name="key"></param>
 54         /// <param name="commandFlags"></param>
 55         /// <returns>T</returns>
 56         T StringGet<T>(string key, CommandFlags commandFlags = CommandFlags.None) where T : class;
 57 
 58         /// <summary>
 59         /// Redis String数据类型 获取指定key中字符串长度
 60         /// </summary>
 61         /// <param name="key"></param>
 62         /// <param name="commandFlags"></param>
 63         /// <returns></returns>
 64         long StringLength(string key, CommandFlags commandFlags = CommandFlags.None);
 65 
 66         /// <summary>
 67         ///  Redis String数据类型  返回拼接后总长度
 68         /// </summary>
 69         /// <param name="key"></param>
 70         /// <param name="appendVal"></param>
 71         /// <param name="commandFlags"></param>
 72         /// <returns>总长度</returns>
 73         long StringAppend(string key, string appendVal, CommandFlags commandFlags = CommandFlags.None);
 74 
 75         /// <summary>
 76         /// 设置新值并且返回旧值
 77         /// </summary>
 78         /// <param name="key"></param>
 79         /// <param name="newVal"></param>
 80         /// <param name="commandFlags"></param>
 81         /// <returns>OldVal</returns>
 82         string StringGetAndSet(string key, string newVal, CommandFlags commandFlags = CommandFlags.None);
 83 
 84         /// <summary>
 85         /// 为数字增长val
 86         /// </summary>
 87         /// <param name="key"></param>
 88         /// <param name="val"></param>
 89         /// <param name="commandFlags"></param>
 90         /// <returns>增长后的值</returns>
 91         double StringIncrement(string key, double val, CommandFlags commandFlags = CommandFlags.None);
 92 
 93         /// <summary>
 94         /// Redis String数据类型
 95         /// 类似于模糊查询  key* 查出所有key开头的键
 96         /// </summary>
 97         /// <typeparam name="T"></typeparam>
 98         /// <param name="key"></param>
 99         /// <param name="pageSize"></param>
100         /// <param name="commandFlags"></param>
101         /// <returns>返回List<T></returns>
102         List<T> StringGetList<T>(string key, int pageSize = 1000, CommandFlags commandFlags = CommandFlags.None) where T : class;
103         #endregion
104 
105 
106         #region Redis各数据类型公用
107 
108         /// <summary>
109         /// Redis中是否存在指定Key
110         /// </summary>
111         /// <param name="key"></param>
112         /// <param name="commandFlags"></param>
113         /// <returns></returns>
114         bool KeyExists(string key, CommandFlags commandFlags = CommandFlags.None);
115 
116         /// <summary>
117         /// 从Redis中移除键
118         /// </summary>
119         /// <param name="key"></param>
120         /// <param name="commandFlags"></param>
121         /// <returns></returns>
122         bool KeyRemove(string key, CommandFlags commandFlags = CommandFlags.None);
123 
124         /// <summary>
125         /// 从Redis中移除多个键
126         /// </summary>
127         /// <param name="keys"></param>
128         /// <param name="commandFlags"></param>
129         /// <returns></returns>
130         void KeyRemove(RedisKey[] keys, CommandFlags commandFlags = CommandFlags.None);
131 
132         /// <summary>
133         /// Dispose DB connection 释放DB相关链接
134         /// </summary>
135         void DbConnectionStop();
136         #endregion
137     }
138 }
  1 #region 程序集 RedisRepository, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  2 // Author:吴双  2016.8.28   联系邮箱 wscoder@outlook.com
  3 #endregion
  4 using System;
  5 using System.Collections.Generic;
  6 using StackExchange.Redis;
  7 
  8 namespace RedisRepository
  9 {
 10     public interface IRedisClient
 11     {
 12         #region Redis String类型操作
 13         /// <summary>
 14         /// Redis String类型 新增一条记录
 15         /// </summary>
 16         /// <typeparam name="T">generic refrence type</typeparam>
 17         /// <param name="key">unique key of value</param>
 18         /// <param name="value">value of key of type object</param>
 19         /// <param name="expiresAt">time span of expiration</param>
 20         /// <param name= "when">枚举类型</param>
 21         /// <param name="commandFlags"></param>
 22         /// <returns>true or false</returns>
 23         bool StringSet<T>(string key, object value, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class;
 24 
 25         /// <summary>
 26         /// Redis String类型 新增一条记录
 27         /// </summary>
 28         /// <typeparam name="T">generic refrence type</typeparam>
 29         /// <param name="key">unique key of value</param>
 30         /// <param name="value">value of key of type object</param>
 31         /// <param name="expiresAt">time span of expiration</param>
 32         /// <param name= "when">枚举类型</param>
 33         /// <param name="commandFlags"></param>
 34         /// <returns>true or false</returns>
 35         bool StringSet<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class;
 36 
 37         /// <summary>
 38         /// 更新时应使用此方法,代码更可读。
 39         /// </summary>
 40         /// <typeparam name="T"></typeparam>
 41         /// <param name="key"></param>
 42         /// <param name="value"></param>
 43         /// <param name="expiresAt"></param>
 44         /// <param name="when"></param>
 45         /// <param name="commandFlags"></param>
 46         /// <returns></returns>
 47         bool StringUpdate<T>(string key, T value, TimeSpan expiresAt, When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class;
 48 
 49         /// <summary>
 50         /// Redis String类型  Get
 51         /// </summary>
 52         /// <typeparam name="T"></typeparam>
 53         /// <param name="key"></param>
 54         /// <param name="commandFlags"></param>
 55         /// <returns>T</returns>
 56         T StringGet<T>(string key, CommandFlags commandFlags = CommandFlags.None) where T : class;
 57 
 58         /// <summary>
 59         /// Redis String数据类型 获取指定key中字符串长度
 60         /// </summary>
 61         /// <param name="key"></param>
 62         /// <param name="commandFlags"></param>
 63         /// <returns></returns>
 64         long StringLength(string key, CommandFlags commandFlags = CommandFlags.None);
 65 
 66         /// <summary>
 67         ///  Redis String数据类型  返回拼接后总长度
 68         /// </summary>
 69         /// <param name="key"></param>
 70         /// <param name="appendVal"></param>
 71         /// <param name="commandFlags"></param>
 72         /// <returns>总长度</returns>
 73         long StringAppend(string key, string appendVal, CommandFlags commandFlags = CommandFlags.None);
 74 
 75         /// <summary>
 76         /// 设置新值并且返回旧值
 77         /// </summary>
 78         /// <param name="key"></param>
 79         /// <param name="newVal"></param>
 80         /// <param name="commandFlags"></param>
 81         /// <returns>OldVal</returns>
 82         string StringGetAndSet(string key, string newVal, CommandFlags commandFlags = CommandFlags.None);
 83 
 84         /// <summary>
 85         /// 为数字增长val
 86         /// </summary>
 87         /// <param name="key"></param>
 88         /// <param name="val"></param>
 89         /// <param name="commandFlags"></param>
 90         /// <returns>增长后的值</returns>
 91         double StringIncrement(string key, double val, CommandFlags commandFlags = CommandFlags.None);
 92 
 93         /// <summary>
 94         /// Redis String数据类型
 95         /// 类似于模糊查询  key* 查出所有key开头的键
 96         /// </summary>
 97         /// <typeparam name="T"></typeparam>
 98         /// <param name="key"></param>
 99         /// <param name="pageSize"></param>
100         /// <param name="commandFlags"></param>
101         /// <returns>返回List<T></returns>
102         List<T> StringGetList<T>(string key, int pageSize = 1000, CommandFlags commandFlags = CommandFlags.None) where T : class;
103         #endregion
104 
105 
106         #region Redis各数据类型公用
107 
108         /// <summary>
109         /// Redis中是否存在指定Key
110         /// </summary>
111         /// <param name="key"></param>
112         /// <param name="commandFlags"></param>
113         /// <returns></returns>
114         bool KeyExists(string key, CommandFlags commandFlags = CommandFlags.None);
115 
116         /// <summary>
117         /// 从Redis中移除键
118         /// </summary>
119         /// <param name="key"></param>
120         /// <param name="commandFlags"></param>
121         /// <returns></returns>
122         bool KeyRemove(string key, CommandFlags commandFlags = CommandFlags.None);
123 
124         /// <summary>
125         /// 从Redis中移除多个键
126         /// </summary>
127         /// <param name="keys"></param>
128         /// <param name="commandFlags"></param>
129         /// <returns></returns>
130         void KeyRemove(RedisKey[] keys, CommandFlags commandFlags = CommandFlags.None);
131 
132         /// <summary>
133         /// Dispose DB connection 释放DB相关链接
134         /// </summary>
135         void DbConnectionStop();
136         #endregion
137     }
138 }

在RedisClient.cs中落实如下:

在RedisClient.cs中贯彻如下:

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace RedisRepository
{
    public class RedisClient : IRedisClient
    {


        #region 初始化

        private static readonly IDatabase _db;
        private static readonly ConnectionMultiplexer _redis;

        /// <summary>
        /// 构造函数,在其中注册Redis事件
        /// </summary>
        static RedisClient()
        {
            const string configuration = "{0},abortConnect=false,defaultDatabase={1},ssl=false,ConnectTimeout={2},allowAdmin=true,connectRetry={3}";
            _redis = ConnectionMultiplexer
                .Connect(string.Format(configuration, RedisClientConfigurations.Url,
                    RedisClientConfigurations.DefaultDatabase, RedisClientConfigurations.ConnectTimeout,
                    RedisClientConfigurations.ConnectRetry));
            _redis.PreserveAsyncOrder = RedisClientConfigurations.PreserveAsyncOrder;
            //_redis.ConnectionFailed;
            _db = _redis.GetDatabase();
        }

        #endregion

        #region Redis String数据类型操作

        /// <summary>
        /// Redis String类型 新增一条记录
        /// </summary>
        /// <typeparam name="T">generic refrence type</typeparam>
        /// <param name="key">unique key of value</param>
        /// <param name="value">value of key of type T</param>
        /// <param name="expiresAt">time span of expiration</param>
        /// <returns>true or false</returns>
        public bool StringSet<T>(string key, T value, TimeSpan? expiresAt = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            var stringContent = SerializeContent(value);
            return _db.StringSet(key, stringContent, expiresAt, when, commandFlags);
        }

        /// <summary>
        /// Redis String类型 新增一条记录
        /// </summary>
        /// <typeparam name="T">generic refrence type</typeparam>
        /// <param name="key">unique key of value</param>
        /// <param name="value">value of key of type object</param>
        /// <param name="expiresAt">time span of expiration</param>
        /// <returns>true or false</returns>
        public bool StringSet<T>(string key, object value, TimeSpan? expiresAt = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            var stringContent = SerializeContent(value);

            return _db.StringSet(key, stringContent, expiresAt, when, commandFlags);
        }

        /// <summary>
        /// Redis String数据类型 获取指定key中字符串长度
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public long StringLength(string key, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.StringLength(key, commandFlags);
        }

        /// <summary>
        ///  Redis String数据类型  返回拼接后总长度
        /// </summary>
        /// <param name="key"></param>
        /// <param name="appendVal"></param>
        /// <returns>总长度</returns>
        public long StringAppend(string key, string appendVal, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.StringAppend(key, appendVal, commandFlags);
        }

        /// <summary>
        /// 设置新值并且返回旧值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="newVal"></param>
        /// <param name="commandFlags"></param>
        /// <returns>OldVal</returns>
        public string StringGetAndSet(string key, string newVal, CommandFlags commandFlags = CommandFlags.None)
        {
            return DeserializeContent<string>(_db.StringGetSet(key, newVal, commandFlags));
        }

        /// <summary>
        /// 更新时应使用此方法,代码更可读。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiresAt"></param>
        /// <param name="when"></param>
        /// <param name="commandFlags"></param>
        /// <returns></returns>
        public bool StringUpdate<T>(string key, T value, TimeSpan expiresAt, When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            var stringContent = SerializeContent(value);
            return _db.StringSet(key, stringContent, expiresAt, when, commandFlags);
        }

        /// <summary>
        /// 为数字增长val
        /// </summary>
        /// <param name="key"></param>
        /// <param name="val">可以为负</param>
        /// <param name="commandFlags"></param>
        /// <returns>增长后的值</returns>
        public double StringIncrement(string key, double val, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.StringIncrement(key, val, commandFlags);
        }

        /// <summary>
        /// Redis String类型  Get
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns>T</returns>
        public T StringGet<T>(string key, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            try
            {
                RedisValue myString = _db.StringGet(key, commandFlags);
                if (myString.HasValue && !myString.IsNullOrEmpty)
                {
                    return DeserializeContent<T>(myString);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                // Log Exception
                return null;
            }
        }

        /// <summary>
        ///  Redis String类型
        /// 类似于模糊查询  key* 查出所有key开头的键
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="pageSize"></param>
        /// <param name="commandFlags"></param>
        /// <returns>List<T></returns>
        public List<T> StringGetList<T>(string key, int pageSize = 1000, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            try
            {
                var server = _redis.GetServer(host: RedisClientConfigurations.Url,
                                              port: RedisClientConfigurations.Port);
                var keys = server.Keys(_db.Database, key, pageSize, commandFlags);
                var keyValues = _db.StringGet(keys.ToArray(), commandFlags);

                var result = new List<T>();
                foreach (var redisValue in keyValues)
                {
                    if (redisValue.HasValue && !redisValue.IsNullOrEmpty)
                    {
                        var item = DeserializeContent<T>(redisValue);
                        result.Add(item);
                    }
                }

                return result;
            }
            catch (Exception)
            {
                // Log Exception
                return null;
            }
        }

        #endregion

        #region Redis Hash散列数据类型操作

        #endregion

        #region Redis List列表数据类型操作

        #endregion

        #region Redis Set集合数据类型操作

        #endregion

        #region Redis Sort Set有序集合数据类型操作

        #endregion

        #region Redis各数据类型公用

        /// <summary>
        /// Redis中是否存在指定Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool KeyExists(string key, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.KeyExists(key, commandFlags);
        }

        /// <summary>
        /// Dispose DB connection 释放DB相关链接
        /// </summary>
        public void DbConnectionStop()
        {
            _redis.Dispose();
        }

        /// <summary>
        /// 从Redis中移除键
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool KeyRemove(string key, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.KeyDelete(key, commandFlags);
        }
        /// <summary>
        /// 从Redis中移除多个键
        /// </summary>
        /// <param name="keys"></param>
        public void KeyRemove(RedisKey[] keys, CommandFlags commandFlags = CommandFlags.None)
        {
            _db.KeyDelete(keys, commandFlags);
        }
        #endregion

        #region 私有公用方法

        // serialize and Deserialize content in separate functions as redis can save value as array of binary. 
        // so, any time you need to change the way of handling value, do it here.

        private string SerializeContent(object value)
        {
            return JsonConvert.SerializeObject(value);
        }

        private T DeserializeContent<T>(RedisValue myString)
        {
            return JsonConvert.DeserializeObject<T>(myString);
        }


        #endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace RedisRepository
{
    public class RedisClient : IRedisClient
    {


        #region 初始化

        private static readonly IDatabase _db;
        private static readonly ConnectionMultiplexer _redis;

        /// <summary>
        /// 构造函数,在其中注册Redis事件
        /// </summary>
        static RedisClient()
        {
            const string configuration = "{0},abortConnect=false,defaultDatabase={1},ssl=false,ConnectTimeout={2},allowAdmin=true,connectRetry={3}";
            _redis = ConnectionMultiplexer
                .Connect(string.Format(configuration, RedisClientConfigurations.Url,
                    RedisClientConfigurations.DefaultDatabase, RedisClientConfigurations.ConnectTimeout,
                    RedisClientConfigurations.ConnectRetry));
            _redis.PreserveAsyncOrder = RedisClientConfigurations.PreserveAsyncOrder;
            //_redis.ConnectionFailed;
            _db = _redis.GetDatabase();
        }

        #endregion

        #region Redis String数据类型操作

        /// <summary>
        /// Redis String类型 新增一条记录
        /// </summary>
        /// <typeparam name="T">generic refrence type</typeparam>
        /// <param name="key">unique key of value</param>
        /// <param name="value">value of key of type T</param>
        /// <param name="expiresAt">time span of expiration</param>
        /// <returns>true or false</returns>
        public bool StringSet<T>(string key, T value, TimeSpan? expiresAt = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            var stringContent = SerializeContent(value);
            return _db.StringSet(key, stringContent, expiresAt, when, commandFlags);
        }

        /// <summary>
        /// Redis String类型 新增一条记录
        /// </summary>
        /// <typeparam name="T">generic refrence type</typeparam>
        /// <param name="key">unique key of value</param>
        /// <param name="value">value of key of type object</param>
        /// <param name="expiresAt">time span of expiration</param>
        /// <returns>true or false</returns>
        public bool StringSet<T>(string key, object value, TimeSpan? expiresAt = default(TimeSpan?), When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            var stringContent = SerializeContent(value);

            return _db.StringSet(key, stringContent, expiresAt, when, commandFlags);
        }

        /// <summary>
        /// Redis String数据类型 获取指定key中字符串长度
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public long StringLength(string key, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.StringLength(key, commandFlags);
        }

        /// <summary>
        ///  Redis String数据类型  返回拼接后总长度
        /// </summary>
        /// <param name="key"></param>
        /// <param name="appendVal"></param>
        /// <returns>总长度</returns>
        public long StringAppend(string key, string appendVal, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.StringAppend(key, appendVal, commandFlags);
        }

        /// <summary>
        /// 设置新值并且返回旧值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="newVal"></param>
        /// <param name="commandFlags"></param>
        /// <returns>OldVal</returns>
        public string StringGetAndSet(string key, string newVal, CommandFlags commandFlags = CommandFlags.None)
        {
            return DeserializeContent<string>(_db.StringGetSet(key, newVal, commandFlags));
        }

        /// <summary>
        /// 更新时应使用此方法,代码更可读。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiresAt"></param>
        /// <param name="when"></param>
        /// <param name="commandFlags"></param>
        /// <returns></returns>
        public bool StringUpdate<T>(string key, T value, TimeSpan expiresAt, When when = When.Always, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            var stringContent = SerializeContent(value);
            return _db.StringSet(key, stringContent, expiresAt, when, commandFlags);
        }

        /// <summary>
        /// 为数字增长val
        /// </summary>
        /// <param name="key"></param>
        /// <param name="val">可以为负</param>
        /// <param name="commandFlags"></param>
        /// <returns>增长后的值</returns>
        public double StringIncrement(string key, double val, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.StringIncrement(key, val, commandFlags);
        }

        /// <summary>
        /// Redis String类型  Get
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns>T</returns>
        public T StringGet<T>(string key, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            try
            {
                RedisValue myString = _db.StringGet(key, commandFlags);
                if (myString.HasValue && !myString.IsNullOrEmpty)
                {
                    return DeserializeContent<T>(myString);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                // Log Exception
                return null;
            }
        }

        /// <summary>
        ///  Redis String类型
        /// 类似于模糊查询  key* 查出所有key开头的键
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="pageSize"></param>
        /// <param name="commandFlags"></param>
        /// <returns>List<T></returns>
        public List<T> StringGetList<T>(string key, int pageSize = 1000, CommandFlags commandFlags = CommandFlags.None) where T : class
        {
            try
            {
                var server = _redis.GetServer(host: RedisClientConfigurations.Url,
                                              port: RedisClientConfigurations.Port);
                var keys = server.Keys(_db.Database, key, pageSize, commandFlags);
                var keyValues = _db.StringGet(keys.ToArray(), commandFlags);

                var result = new List<T>();
                foreach (var redisValue in keyValues)
                {
                    if (redisValue.HasValue && !redisValue.IsNullOrEmpty)
                    {
                        var item = DeserializeContent<T>(redisValue);
                        result.Add(item);
                    }
                }

                return result;
            }
            catch (Exception)
            {
                // Log Exception
                return null;
            }
        }

        #endregion

        #region Redis Hash散列数据类型操作

        #endregion

        #region Redis List列表数据类型操作

        #endregion

        #region Redis Set集合数据类型操作

        #endregion

        #region Redis Sort Set有序集合数据类型操作

        #endregion

        #region Redis各数据类型公用

        /// <summary>
        /// Redis中是否存在指定Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool KeyExists(string key, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.KeyExists(key, commandFlags);
        }

        /// <summary>
        /// Dispose DB connection 释放DB相关链接
        /// </summary>
        public void DbConnectionStop()
        {
            _redis.Dispose();
        }

        /// <summary>
        /// 从Redis中移除键
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool KeyRemove(string key, CommandFlags commandFlags = CommandFlags.None)
        {
            return _db.KeyDelete(key, commandFlags);
        }
        /// <summary>
        /// 从Redis中移除多个键
        /// </summary>
        /// <param name="keys"></param>
        public void KeyRemove(RedisKey[] keys, CommandFlags commandFlags = CommandFlags.None)
        {
            _db.KeyDelete(keys, commandFlags);
        }
        #endregion

        #region 私有公用方法

        // serialize and Deserialize content in separate functions as redis can save value as array of binary. 
        // so, any time you need to change the way of handling value, do it here.

        private string SerializeContent(object value)
        {
            return JsonConvert.SerializeObject(value);
        }

        private T DeserializeContent<T>(RedisValue myString)
        {
            return JsonConvert.DeserializeObject<T>(myString);
        }


        #endregion
    }
}

上面不难介绍一下本文中的方法细节之处。

下边简单介绍一下本文中的方法细节之处。

第③在RedisClient类的构造方法中开头化Redis数据操作对象_db。各样方法越多的事无巨细新闻请留心格局注释。假使有关Redis命令还不打听,请看中期Redis命令拾遗名目繁多小说
http://www.cnblogs.com/tdws/tag/NoSql/

先是在RedisClient类的构造方法中伊始化Redis数据操作对象_db。每一个方法越来越多的事无巨细消息请留心方法注释。要是有关Redis命令还不明白,请看前期Redis命令拾遗多如牛毛小说
http://www.cnblogs.com/tdws/tag/NoSql/

 

 

有园友提出难点说

有园友建议难点说

Because the ConnectionMultiplexer does a lot, it is designed to be
shared and reused between callers. You should not create a
ConnectionMultiplexer per operation. It is fully thread-safe and ready
for this usage.
那是法定文书档案的原话,ConnectionMultiplexer相比“重”,提议共用,不要老是操作就创办八个

Because the ConnectionMultiplexer does a lot, it is designed to be
shared and reused between callers. You should not create a
ConnectionMultiplexer per operation. It is fully thread-safe and ready
for this usage.
那是合法文档的原话,ConnectionMultiplexer相比较“重”,提出共用,不要老是操作就制造二个

据此一时将构造函数改为静态构造。假如格外,欢迎提之处

为此一时将构造函数改为静态构造。假设有标题,欢迎提之处

 

 

21日,反思了一晃,依然加锁的单例更为适宜。

一日,反思了一下,依然加锁的单例更为贴切。

相关文章