码迷,mamicode.com
首页 > 其他好文 > 详细

StackExchange.Redis数据操作封装(简单Key/Value存储操作)(原创)

时间:2018-05-14 19:54:17      阅读:929      评论:0      收藏:0      [点我收藏+]

标签:readwrite   sys   文件中   else   reac   数据操作   类库   settime   ddr   

接口:

using System;
using System.Collections.Generic;
using System.Text;

namespace YesWay.Redis
{
    /// <summary>
    /// NedisClient对外开放的方法
    /// </summary>
    public interface ICache
    {
        #region 简单Key/Value存储操作
        /// <summary>
        /// 字符串的新增或修改
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns>true or false</returns>
        bool Set(string key, string value);

        /// <summary>
        /// 如果key不存在,则设置
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        bool SetNX(string key, string value);

        /// <summary>
        /// 字符串的新增或修改 并设置过期时间
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns>true or false</returns>
        bool Set(string key, string value, DateTime expireTime);

        /// <summary>
        /// 设置redis 缓存过期时间
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="expireTime">时间</param>
        /// <returns></returns>
        bool SetTimeOut(string key, DateTime expireTime);

        /// <summary>
        /// 设置redis 缓存过期时间
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="expireTimeSpan">时间</param>
        /// <returns></returns>
        bool SetTimeOut(string key, TimeSpan expireTimeSpan);

        /// <summary>
        /// 根据输入的多个Key获取多个值,支持泛型
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="keys">多个Key</param>
        /// <returns>多个值</returns>
        List<T> MGet<T>(List<string> keys);


        /// <summary>
        /// 输入一个字典集合批量插入数据
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="values">values</param>
        void MSet<T>(IDictionary<string, T> values);

        /// <summary>
        /// 根据输入的多个Key获取多个值,支持泛型
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="keys">多个Key</param>
        /// <returns>字典集合</returns>
        IDictionary<string, T> MGetDictionary<T>(List<string> keys);

        /// <summary>
        /// 字符串的查询
        /// </summary>
        /// <param name="key"></param>
        /// <returns>Value</returns>
        string Get(string key);


        ///// <summary>
        ///// 获取key对应的原始值(未经过JSON序列化处理)
        ///// </summary>
        ///// <param name="key"></param>
        ///// <returns></returns>
        //string GetOriginal(string key);

        ///// <summary>
        ///// 获取指定key的指定范围的字符串
        ///// </summary>
        ///// <param name="key"></param>
        ///// <param name="start">如果是序列化为Json的字符串,则从1开始,否则从0开始</param>
        ///// <param name="end"></param>
        ///// <returns>Value</returns>
        //string GetRange(string key, int start, int end);


        /// <summary>
        /// 范型数据的新增或修改
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns>true or false</returns>
        bool Set<T>(string key, T value);


        /// <summary>
        /// 范型数据的查询
        /// </summary>
        /// <param name="key"></param>
        /// <returns>value</returns>
        T Get<T>(string key);


        ///// <summary>
        ///// 删除
        ///// </summary>
        ///// <param name="key">key</param>
        ///// <returns>true or false</returns>
        //bool Remove(string key);

        ///// <summary>
        ///// 验证Key是否存在
        ///// </summary>
        ///// <param name="key"></param>
        ///// <returns>true or false</returns>
        //bool Exists(string key);

        ///// <summary>
        ///// 字符串的追加
        ///// </summary>
        ///// <param name="key">key</param>
        ///// <param name="value">value</param>
        ///// <returns>true or false</returns>
        //long Append(string key, string value);

        ///// <summary>
        ///// 获取指定Key的过期时间
        ///// </summary>
        ///// <param name="key"></param>
        ///// <returns></returns>
        //TimeSpan GetTimeToLive(string key);

        #endregion
    }
}

  实现:

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

namespace YesWay.Redis
{
    /// <summary>
    /// NedisClient
    /// </summary>
    public class NedisClient : ICache
    {
        /// <summary>
        /// 默认超时时间(单位秒)
        /// </summary>
        //int Default_Timeout = 600;

        /// <summary>
        /// Redis数据服务器地址:ip:port,ip:port
        /// </summary>
        string address;
        JsonSerializerSettings jsonConfig = new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore };

        /// <summary>
        /// StackExchange类库操作Redis数据库的类对象
        /// </summary>
        ConnectionMultiplexer connectionMultiplexer;

        /// <summary>
        /// Redis数据库
        /// </summary>
        IDatabase database;

        class CacheObject<T>
        {
            public int ExpireTime { get; set; }
            public bool ForceOutofDate { get; set; }
            public T Value { get; set; }
        }

        /// <summary>
        /// 无参构造方法
        /// </summary>
        public NedisClient()
        {
            this.address = ConfigurationManager.AppSettings["RedisServer"];

            if (this.address == null || string.IsNullOrWhiteSpace(this.address.ToString()))
                throw new ApplicationException("配置文件中未找到RedisServer的有效配置");
            connectionMultiplexer = ConnectionMultiplexer.Connect(address);
            database = connectionMultiplexer.GetDatabase();
        }

        #region 简单Key/Value存储操作
        /// <summary>
        /// 字符串的新增或修改
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns>true or false</returns>
        public bool Set(string key, string value)
        {
            try
            {
                return database.StringSet(key, value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 如果key不存在,则设置
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetNX(string key, string value)
        {
            try
            {
                return database.StringSet(key, value,null, When.NotExists);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        

        /// <summary>
        /// 字符串的新增或修改 并设置过期时间
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns>true or false</returns>
        public bool Set(string key, string value, DateTime expireTime)
        {
            try
            {
                database.StringSet(key, value);
                database.KeyExpire(key, expireTime);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 设置redis 缓存过期时间
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="expireTime">时间</param>
        /// <returns></returns>
        public bool SetTimeOut(string key, DateTime expireTime)
        {
            try
            {
                database.KeyExpire(key, expireTime);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 设置redis 缓存过期时间
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="expireTimeSpan">时间</param>
        /// <returns></returns>
        public bool SetTimeOut(string key, TimeSpan expireTimeSpan)
        {
            try
            {
                database.KeyExpire(key, expireTimeSpan);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据输入的多个Key获取多个值,支持泛型  StackExchange版本T支持byte[],NserverKit版本报错
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="keys">多个Key</param>
        /// <returns>多个值</returns>
        public List<T> MGet<T>(List<string> keys)
        {
            if (keys != null && keys.Count > 100)
            {
                throw new Exception("Key的个数不能大于100个");
            }
            try
            {
                //if (redisConfig.ReadWriteSeparate)
                //{
                //    client = redisClientsManagers[index].GetReadOnlyClient();
                //}
                //else
                //{
                //    client = redisClientsManagers[index].GetClient();
                //}
                var bytesArray = database.StringGet(keys.Select(i => (RedisKey)i).ToArray());
                var results = new List<T>();
                var isBytes = typeof(T) == typeof(byte[]);

                foreach (var resultBytes in bytesArray)
                {
                    if (resultBytes.IsNull) continue;

                    if (isBytes)
                    {
                        var result=Encoding.Default.GetBytes(Encoding.UTF8.GetString(resultBytes));
                        results.Add((T)(object)result);
                    }
                    else
                    {
                        var resultString = Encoding.UTF8.GetString(resultBytes);
                        if (typeof(T) == typeof(String) && !resultString.StartsWith("\""))
                        {
                            resultString = "\"" + resultString + "\"";
                        }
                        var result = JsonConvert.DeserializeObject<T>(resultString);
                        results.Add(result);
                    }
                }
                return results;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据输入的多个Key获取多个值,支持泛型
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="keys">多个Key</param>
        /// <returns>字典集合</returns>
        public IDictionary<string, T> MGetDictionary<T>(List<string> keys)
        {
            if (keys != null && keys.Count > 100)
            {
                throw new Exception("Key的个数不能大于100个");
            }
            try
            {
                //if (redisConfig.ReadWriteSeparate)
                //{
                //    client = redisClientsManagers[index].GetReadOnlyClient();
                //}
                //else
                //{
                //    client = redisClientsManagers[index].GetClient();
                //}
                var keysArray = keys.ToArray();
                var keyValues = database.StringGet(keys.Select(key => (RedisKey)key).ToArray());
                var results = new Dictionary<string, T>();
                var isBytes = typeof(T) == typeof(byte[]);

                var i = 0;
                foreach (var keyValue in keyValues)
                {
                    var key = keysArray[i++];

                    if (keyValue.IsNull)
                    {
                        results[key] = default(T);
                        continue;
                    }

                    if (isBytes)
                    {
                        results[key] = (T)(object)Encoding.Default.GetBytes(Encoding.UTF8.GetString(keyValue));
                    }
                    else
                    {
                        var keyValueString = Encoding.UTF8.GetString(keyValue);
                        if (typeof(T) == typeof(String) && !keyValueString.StartsWith("\""))
                        {
                            keyValueString = "\"" + keyValueString + "\"";
                        }
                        results[key] = JsonConvert.DeserializeObject<T>(keyValueString);
                    }
                }
                return results;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 输入一个字典集合批量插入数据
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="values">values</param>
        public void MSet<T>(IDictionary<string, T> values)
        {
            if (values != null && values.Count > 100)
            {
                throw new Exception("Values的个数不能大于100个");
            }
            try
            {
                //if (redisConfig.ReadWriteSeparate)
                //{
                //    client = redisClientsManagers[index].GetReadOnlyClient();
                //}
                //else
                //{
                //    client = redisClientsManagers[index].GetClient();
                //}
                foreach (var kvp in values)
                {
                    Set<T>(kvp.Key,kvp.Value);
                }
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 字符串的查询
        /// </summary>
        /// <param name="key"></param>
        /// <returns>Value</returns>
        public string Get(string key)
        {
            try
            {
                //if (redisConfig.ReadWriteSeparate)
                //{
                //    client = redisClientsManagers[index].GetReadOnlyClient();
                //}
                //else
                //{
                //    client = redisClientsManagers[index].GetClient();
                //}

                return Get<string>(key);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 范型数据的新增或修改
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns>true or false</returns>
        public bool Set<T>(string key, T value)
        {
            try
            {
                var bytesValue = value as byte[];
                if (bytesValue != null)
                {
                    database.StringSet(key, bytesValue);
                    return true;
                }

                var valueString = JsonConvert.SerializeObject(value);
                database.StringSet(key, valueString);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 范型数据的查询
        /// StackExchange版本可以查询byte[]类型数据  NserviceKit不能查询byte[]类型数据 死循环
        /// NserviceKit:client.Get<string>("mset112");如果key不存在 报错
        /// </summary>
        /// <param name="key"></param>
        /// <returns>value</returns>
        public T Get<T>(string key)
        {
            try
            {
                //if (redisConfig.ReadWriteSeparate)
                //{
                //    client = redisClientsManagers[index].GetReadOnlyClient();
                //}
                //else
                //{
                //    client = redisClientsManagers[index].GetClient();
                //}
                var result = database.StringGet(key);
                if (result.IsNull)
                {
                    return default(T);
                }
                if (typeof(T) == typeof(byte[]))
                {
                    return (T)(object)Encoding.Default.GetBytes(Encoding.UTF8.GetString(result));
                }
                else
                {
                    var keyValueString = Encoding.UTF8.GetString(result);
                    if (typeof(T) == typeof(String) && !keyValueString.StartsWith("\""))
                    {
                        keyValueString = "\"" + keyValueString + "\"";
                    }
                    if (!string.IsNullOrWhiteSpace(keyValueString))
                    {
                        return JsonConvert.DeserializeObject<T>(keyValueString);
                    }
                    return default(T);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}

  测试:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YesWay.RedisTest
{
    class Program
    {
        static void Main(string[] args)
        {
            YesWay.Redis.NedisClient client = new YesWay.Redis.NedisClient();

            #region 简单Key/Value存储操作
            // 字符串的新增或修改
            // public bool Set(string key, string value)
            //client.Set("liu", "liuqiyun");

            // 如果key不存在,则设置
            // bool SetNX(string key, string value);
            //client.SetNX("liu1", "11111111111");

            // 字符串的新增或修改 并设置过期时间
            // bool Set(string key, string value, DateTime expireTime);
            //client.Set("qq", "liuqiyun"+ DateTime.Now.ToString(), DateTime.Now.AddMinutes(1));

            // 设置redis 缓存过期时间
            // public bool SetTimeOut(string key, DateTime expireTime)
            //client.SetTimeOut("liu1",  DateTime.Now.AddMinutes(1));

            // 设置redis 缓存过期时间
            // bool SetTimeOut(string key, TimeSpan expireTimeSpan);
            //client.SetTimeOut("liu", DateTime.Now.AddSeconds(30) - DateTime.Now);

            // 根据输入的多个Key获取多个值,支持泛型
            // public List<T> MGet<T>(List<string> keys)
            //var listKey = new List<string>();
            //listKey.Add("mset111");
            //listKey.Add("mset222");
            //listKey.Add("mset2221");
            //var listPerson = client.MGet<Person>(listKey);
            //Console.WriteLine(listPerson.Count);
            //foreach (var person in listPerson)
            //{
            //    Console.WriteLine(person.UserName + person.PassWord);
            //}

            //var listKey = new List<string>();
            //listKey.Add("mset1");
            //listKey.Add("mset2");
            //listKey.Add("mset2123123");
            //var listString = client.MGet<string>(listKey);
            //Console.WriteLine(listString.Count);
            //foreach (var stringkey in listString)
            //{
            //    Console.WriteLine(stringkey);
            //}

            //var listKey = new List<string>();
            //listKey.Add("mset11");
            //listKey.Add("mset22");
            //listKey.Add("mset2123123");
            //var listByte = client.MGet<byte[]>(listKey);
            //Console.WriteLine(listByte.Count);
            //foreach (var bytekey in listByte)
            //{
            //    Console.WriteLine(Encoding.UTF8.GetString(bytekey));
            //}
            //Console.ReadKey();


            // 输入一个字典集合批量插入数据
            // public void MSet<T>(IDictionary<string, T> values)
            //Dictionary<string, string> d1 = new Dictionary<string, string>();
            //d1.Add("mset1", "mset1value");
            //d1.Add("mset2", "mset1value2");
            //client.MSet<string>(d1);
            //Dictionary<string, byte[]> d2 = new Dictionary<string, byte[]>();
            //d2.Add("mset11", System.Text.Encoding.ASCII.GetBytes("mset1value"));
            //d2.Add("mset22", System.Text.Encoding.ASCII.GetBytes("mset1value2"));
            //client.MSet<byte[]>(d2);
            //Dictionary<string, Person> d3 = new Dictionary<string, Person>();
            //d3.Add("mset111", new Person { UserName = "\"liu", PassWord = "1234" });
            //d3.Add("mset222", new Person { UserName = "\"liu", PassWord = "abcs" });
            //client.MSet<Person>(d3);


            // 根据输入的多个Key获取多个值,支持泛型
            // public IDictionary<string, T> MGetDictionary<T>(List<string> keys)
            //var listKey = new List<string>();
            //listKey.Add("mset11");
            //listKey.Add("mset22");
            //listKey.Add("mset2123123");
            //var dcString = client.MGetDictionary<string>(listKey);
            //Console.WriteLine(dcString.Keys.Count);
            //foreach (var stringkey in dcString)
            //{
            //    //if (stringkey.Value != null)
            //    Console.WriteLine(stringkey.Key + ":" + stringkey.Value);
            //}
            //var listKey = new List<string>();
            //listKey.Add("mset111");
            //listKey.Add("mset222");
            //listKey.Add("mset2221");
            //var dcPerson = client.MGetDictionary<Person>(listKey);
            //Console.WriteLine(dcPerson.Keys.Count);
            //foreach (var person in dcPerson)
            //{
            //    if (person.Value != null)
            //        Console.WriteLine(person.Key + ":" + person.Value.UserName + person.Value.PassWord);
            //}
            //var listKey = new List<string>();
            //listKey.Add("mset11");
            //listKey.Add("mset22");
            //listKey.Add("mset2123123");
            //var dcByte = client.MGetDictionary<byte[]>(listKey);
            //Console.WriteLine(dcByte.Keys.Count);
            //foreach (var bytekey in dcByte)
            //{
            //    if (bytekey.Value != null)
            //        Console.WriteLine(bytekey.Key + ":" + Encoding.UTF8.GetString(bytekey.Value));
            //}
            //Console.ReadKey();

            // 字符串的查询 范型数据的查询
            // public string Get(string key)
            // public T Get<T>(string key)
            //Console.WriteLine(client.Get("mset11"));
            //Console.WriteLine(Encoding.UTF8.GetString(client.Get<byte[]>("mset11")));
            //Console.WriteLine(client.Get("mset11"));
            //Console.WriteLine(Encoding.UTF8.GetString(client.Get<byte[]>("mset11")));
            //var result = client.Get("mset1");
            //Console.WriteLine(result);


            // 范型数据的新增或修改
            // public bool Set<T>(string key, T value)
            //var key = "qaz";
            //var value = new Person { UserName = "liu", PassWord = "1234" };
            //client.Set<Person>(key, value);

            //var key1 = "byte1";
            //byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(key1);
            //client.Set<byte[]>(key1, byteArray);
            //var key2 = "byteString";
            //client.Set<string>(key2, key1);
            #endregion

            Console.ReadKey();
        }
    }
    public class Person
    {
        public string UserName { get; set; }
        public string PassWord { get; set; }
    }
}

  

StackExchange.Redis数据操作封装(简单Key/Value存储操作)(原创)

标签:readwrite   sys   文件中   else   reac   数据操作   类库   settime   ddr   

原文地址:https://www.cnblogs.com/liuqiyun/p/9037703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!