【redis学习总结】C# StackExchange Redis

链接: https://pan.baidu.com/s/1lZ0vGsQb4CHrPIdO26Q8pg 密码: fvnb

文件在这里,有兴趣可以看看

先一步一步封装吧。

首先是ConfigurationHelper

public static class ConfigurationHelper
    {
        internal static T Get(string appSettingsKey, T defaultValue)
        {
            string text = ConfigurationManager.AppSettings[appSettingsKey];
            if (string.IsNullOrWhiteSpace(text))
                return defaultValue;
            try
            {
                var value = Convert.ChangeType(text, typeof(T));
                return (T)value;
            }
            catch
            {
                return defaultValue;
            }
        }
    }

下面是RedisClientConfigurations

private static string _url = ConfigurationHelper.Get("RedisServer", "127.0.0.1");
        public static string Url
        {
            get { return _url; }
            set { _url = value; }
        }

        private static int _port = 7000;
        public static int Port
        {
            get { return _port; }
            set { _port = value; }
        }

        private static int _connectTimeout = 10000;
        public static int ConnectTimeout
        {
            get { return _connectTimeout; }
            set { _connectTimeout = value; }
        }

        private static int _connectRetry = 3;
        public static int ConnectRetry
        {
            get { return _connectRetry; }
            set { _connectRetry = value; }
        }

        private static int _defaultDatabase = ConfigurationHelper.Get("RedisDataBase", 0);
        public static int DefaultDatabase
        {
            get { return _defaultDatabase; }
            set { _defaultDatabase = value; }
        }

        private static bool _preserveAsyncOrder = false;
        public static bool PreserveAsyncOrder
        {
            get { return _preserveAsyncOrder; }
            set { _preserveAsyncOrder = value; }
        }
    }

RedisClient:

static RedisClient()
        {
            ConfigurationOptions option = new ConfigurationOptions();
            option.EndPoints.Add("127.0.0.1", 7005);
            _redis = ConnectionMultiplexer.Connect(option);
            _db = _redis.GetDatabase();
        }
#region 私有公用方法   在其中我们序列化操作使用Newtonsoft.Json组件

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

        private T DeserializeContent(RedisValue myString)
        {
            return JsonConvert.DeserializeObject(myString);
        }
        /// 
        /// string类型存值并设置过期时间
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static bool Set(string key, T t, TimeSpan ts)
        {
            var str = JsonConvert.SerializeObject(t);
            return _db.StringSet(key, str,ts);
        }

        #endregion

string类型的封装
#region Redis String数据类型操作

        /// 
        /// Redis String类型 新增一条记录
        /// 
        /// generic refrence type
        /// unique key of value
        /// value of key of type T
        /// time span of expiration
        /// true or false
        public bool StringSet(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);
        }

        /// 
        /// Redis String类型 新增一条记录
        /// 
        /// generic refrence type
        /// unique key of value
        /// value of key of type object
        /// time span of expiration
        /// true or false
        public bool StringSet(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);
        }

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

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

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

        /// 
        /// 更新时应使用此方法,代码更可读。
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool StringUpdate(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);
        }

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

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

        /// 
        ///  Redis String类型
        /// 类似于模糊查询  key* 查出所有key开头的键
        /// 
        /// 
        /// 
        /// 
        /// 
        /// List
        public List StringGetList(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();
                foreach (var redisValue in keyValues)
                {
                    if (redisValue.HasValue && !redisValue.IsNullOrEmpty)
                    {
                        var item = DeserializeContent(redisValue);
                        result.Add(item);
                    }
                }

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

        #endregion


hash类型的封装

#region Redis Hash散列数据类型操作
        /// 
        /// Redis散列数据类型  批量新增
        /// 
        /// 
        /// 
        /// 
        public void HashSet(string key, List hashEntrys, CommandFlags flags = CommandFlags.None)
        {
            _db.HashSet(key, hashEntrys.ToArray(), flags);
        }
        /// 
        /// Redis散列数据类型  新增一个
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public void HashSet(string key, string field, T val, When when = When.Always, CommandFlags flags = CommandFlags.None)
        {
            _db.HashSet(key, field, SerializeContent(val), when, flags);
        }
        //public HashEntry[] HashScan(string key, string pattern, int pagesize, CommandFlags flags = CommandFlags.None)
        //{
        //    return _db.HashScan(key, pattern, pagesize, flags);
        //}

        public async Task HashSetAsync(string key, string field, T val, When when = When.Always, CommandFlags flags = CommandFlags.None)
        {
            await _db.HashSetAsync(key, field, SerializeContent(val), when, flags);
        }
        /// 
        /// Redis散列数据类型 获取指定key的指定field
        /// 
        /// 
        /// 
        /// 
        /// 
        public T HashGet(string key, string field)
        {
            return DeserializeContent(_db.HashGet(key, field));
        }
        /// 
        /// Redis散列数据类型 获取所有field所有值,以 HashEntry[]形式返回
        /// 
        /// 
        /// 
        /// 
        public HashEntry[] HashGetAll(string key, CommandFlags flags = CommandFlags.None)
        {
            return _db.HashGetAll(key, flags);
        }
        /// 
        /// 一个有问题的迭代器,可以便利hash key的全部元素
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public List HashScan(string key,string pattern, int pageSize)
        {
            List list = new List();
            var hashVals = _db.HashScan(key, pattern, pageSize).ToList();
            foreach(var item in hashVals)
            {
                list.Add(DeserializeContent(item.Value));
            }
            return list;
        }
        /// 
        /// Redis散列数据类型 获取key中所有field的值。
        /// 
        /// 
        /// 
        /// 
        /// 
        public List HashGetAllValues(string key, CommandFlags flags = CommandFlags.None)
        {
            List list = new List();
            var hashVals = _db.HashValues(key, flags).ToList();
            foreach (var item in hashVals)
            {
                list.Add(DeserializeContent(item));
            }
            return list;
        }

        public void HashScan(string key,string pattern,int pagesize)
        {
            _db.HashScan(key, pattern, pagesize);
        }

        public async Task> HashGetAllValuseAsync(string key, CommandFlags flags = CommandFlags.None)
        {
            List list = new List();
            var hashVals = await _db.HashValuesAsync(key, flags);
            foreach(var item in hashVals)
            {
                list.Add(DeserializeContent(item));
            }
            return list;
        }
        /// 
        /// Redis散列数据类型 获取所有Key名称
        /// 
        /// 
        /// 
        /// 
        public string[] HashGetAllKeys(string key, CommandFlags flags = CommandFlags.None)
        {
            return _db.HashKeys(key, flags).ToStringArray();
        }
        /// 
        /// Redis散列数据类型  单个删除field
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool HashDelete(string key, string hashField, CommandFlags flags = CommandFlags.None)
        {
            return _db.HashDelete(key, hashField, flags);
        }
        /// 
        /// Redis散列数据类型  批量删除field
        /// 
        /// 
        /// 
        /// 
        /// 
        public long HashDelete(string key, string[] hashFields, CommandFlags flags = CommandFlags.None)
        {
            List list = new List();
            for (int i = 0; i < hashFields.Length; i++)
            {
                list.Add(hashFields[i]);
            }
            return _db.HashDelete(key, list.ToArray(), flags);
        }
        /// 
        /// Redis散列数据类型 判断指定键中是否存在此field
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool HashExists(string key, string field, CommandFlags flags = CommandFlags.None)
        {
            return _db.HashExists(key, field, flags);
        }
        /// 
        /// Redis散列数据类型  获取指定key中field数量
        /// 
        /// 
        /// 
        /// 
        public long HashLength(string key, CommandFlags flags = CommandFlags.None)
        {
            return _db.HashLength(key, flags);
        }
        /// 
        /// Redis散列数据类型  为key中指定field增加incrVal值
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public double HashIncrement(string key, string field, double incrVal, CommandFlags flags = CommandFlags.None)
        {
            return _db.HashIncrement(key, field, incrVal, flags);
        }

        #endregion

hash类型中可以使用scan这个迭代器对hash类型进行模糊查询,效率很高。有兴趣可以对我使用。

这是我主要使用的两个类型,其他类型暂时没用到=-=,也没有收集,不过网上会有很多。

你可能感兴趣的:(redis)