c#使用 StackExchange.Redis 封装 RedisHelper

c#使用 StackExchange.Redis 封装 RedisHelper_第1张图片

1.定义ICache接口。

2.Redis类和Memcached类,以后想用那个缓存修改一下配置就可以了,非常方便。

3.CacheHelper的实现。

上代码:

ICache.cs

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

namespace Common
{
    public interface ICache
    {
        /// 
        /// 缓存过期时间
        /// 
        int TimeOut { set; get; }
        /// 
        /// 获得指定键的缓存值
        /// 
        /// 缓存键
        /// 缓存值
        object Get(string key);
        /// 
        /// 获得指定键的缓存值
        /// 
        T Get(string key);
        /// 
        /// 从缓存中移除指定键的缓存值
        /// 
        /// 缓存键
        void Remove(string key);
        /// 
        /// 清空所有缓存对象
        /// 
        //void Clear();
        /// 
        /// 将指定键的对象添加到缓存中
        /// 
        /// 缓存键
        /// 缓存值
        void Insert(string key, object data);
        /// 
        /// 将指定键的对象添加到缓存中
        /// 
        /// 缓存键
        /// 缓存值
        void Insert(string key, T data);
        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间(秒钟)
        void Insert(string key, object data, int cacheTime);

        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间(秒钟)
        void Insert(string key, T data, int cacheTime);
        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间
        void Insert(string key, object data, DateTime cacheTime);
        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间
        void Insert(string key, T data, DateTime cacheTime);
        /// 
        /// 判断key是否存在
        /// 
        bool Exists(string key);
    }
}

Redis.cs

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

namespace Common
{
    public class Redis : ICache
    {
        int Default_Timeout = 600;//默认超时时间(单位秒)
        string address;
        JsonSerializerSettings jsonConfig = new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore };
        ConnectionMultiplexer connectionMultiplexer;
        IDatabase database;

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

        public Redis()
        {
            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();
        }

        /// 
        /// 连接超时设置
        /// 
        public int TimeOut
        {
            get
            {
                return Default_Timeout;
            }
            set
            {
                Default_Timeout = value;
            }
        }

        public object Get(string key)
        {
            return Get(key);
        }

        public T Get(string key)
        {

            DateTime begin = DateTime.Now;
            var cacheValue = database.StringGet(key);
            DateTime endCache = DateTime.Now;
            var value = default(T);
            if (!cacheValue.IsNull)
            {
                var cacheObject = JsonConvert.DeserializeObject>(cacheValue, jsonConfig);
                if (!cacheObject.ForceOutofDate)
                    database.KeyExpire(key, new TimeSpan(0, 0, cacheObject.ExpireTime));
                value = cacheObject.Value;
            }
            DateTime endJson = DateTime.Now;
            return value;

        }

        public void Insert(string key, object data)
        {
            var jsonData = GetJsonData(data, TimeOut, false);
            database.StringSet(key, jsonData);
        }

        public void Insert(string key, object data, int cacheTime)
        {
            var timeSpan = TimeSpan.FromSeconds(cacheTime);
            var jsonData = GetJsonData(data, TimeOut, true);
            database.StringSet(key, jsonData, timeSpan);
        }

        public void Insert(string key, object data, DateTime cacheTime)
        {
            var timeSpan = cacheTime - DateTime.Now;
            var jsonData = GetJsonData(data, TimeOut, true);
            database.StringSet(key, jsonData, timeSpan);
        }

        public void Insert(string key, T data)
        {
            var jsonData = GetJsonData(data, TimeOut, false);
            database.StringSet(key, jsonData);
        }

        public void Insert(string key, T data, int cacheTime)
        {
            var timeSpan = TimeSpan.FromSeconds(cacheTime);
            var jsonData = GetJsonData(data, TimeOut, true);
            database.StringSet(key, jsonData, timeSpan);
        }

        public void Insert(string key, T data, DateTime cacheTime)
        {
            var timeSpan = cacheTime - DateTime.Now;
            var jsonData = GetJsonData(data, TimeOut, true);
            database.StringSet(key, jsonData, timeSpan);
        }


        string GetJsonData(object data, int cacheTime, bool forceOutOfDate)
        {
            var cacheObject = new CacheObject() { Value = data, ExpireTime = cacheTime, ForceOutofDate = forceOutOfDate };
            return JsonConvert.SerializeObject(cacheObject, jsonConfig);//序列化对象
        }

        string GetJsonData(T data, int cacheTime, bool forceOutOfDate)
        {
            var cacheObject = new CacheObject() { Value = data, ExpireTime = cacheTime, ForceOutofDate = forceOutOfDate };
            return JsonConvert.SerializeObject(cacheObject, jsonConfig);//序列化对象
        }
        /// 
        /// 删除
        /// 
        /// 
        public void Remove(string key)
        {
            database.KeyDelete(key, CommandFlags.HighPriority);
        }

        /// 
        /// 判断key是否存在
        /// 
        public bool Exists(string key)
        {
            return database.KeyExists(key);
        }
     
    }
} 
  

CacheHelper.cs

using System;
using System.Collections.Generic;

namespace Common
{
    /// 
    /// 缓存
    /// 
    public static class Cache
    {
        private static object cacheLocker = new object();//缓存锁对象
        private static ICache cache = null;//缓存接口
        
        static Cache()
        {
            Load();
        }

        /// 
        /// 加载缓存
        /// 
        /// 
        private static void Load()
        {
            try
            {
               cache = new Redis();
            }
            catch (Exception ex)
            {
                //Log.Error(ex.Message);
            }
        }

        public static ICache GetCache()
        {
            return cache;
        }


        /// 
        /// 缓存过期时间
        /// 
        public static int TimeOut
        {
            get
            {
                return cache.TimeOut;
            }
            set
            {
                lock (cacheLocker)
                {
                    cache.TimeOut = value;
                }
            }
        }

        /// 
        /// 获得指定键的缓存值
        /// 
        /// 缓存键
        /// 缓存值
        public static object Get(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                return null;
            return cache.Get(key);
        }

        /// 
        /// 获得指定键的缓存值
        /// 
        /// 缓存键
        /// 缓存值
        public static T Get(string key)
        {
            return cache.Get(key);
        }

        /// 
        /// 将指定键的对象添加到缓存中
        /// 
        /// 缓存键
        /// 缓存值
        public static void Insert(string key, object data)
        {
            if (string.IsNullOrWhiteSpace(key) || data == null)
                return;
            //lock (cacheLocker)
            {
                cache.Insert(key, data);
            }
        }
        /// 
        /// 将指定键的对象添加到缓存中
        /// 
        /// 缓存键
        /// 缓存值
        public static void Insert(string key, T data)
        {
            if (string.IsNullOrWhiteSpace(key) || data == null)
                return;
            //lock (cacheLocker)
            {
                cache.Insert(key, data);
            }
        }
        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间(分钟)
        public static void Insert(string key, object data, int cacheTime)
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.Insert(key, data, cacheTime);
                }
            }
        }

        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间(分钟)
        public static void Insert(string key, T data, int cacheTime)
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.Insert(key, data, cacheTime);
                }
            }
        }

        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间
        public static void Insert(string key, object data, DateTime cacheTime)
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.Insert(key, data, cacheTime);
                }
            }
        }

        /// 
        /// 将指定键的对象添加到缓存中,并指定过期时间
        /// 
        /// 缓存键
        /// 缓存值
        /// 缓存过期时间
        public static void Insert(string key, T data, DateTime cacheTime)
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.Insert(key, data, cacheTime);
                }
            }
        }

        /// 
        /// 从缓存中移除指定键的缓存值
        /// 
        /// 缓存键
        public static void Remove(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                return;
            lock (cacheLocker)
            {
                cache.Remove(key);
            }
        }

        /// 
        /// 判断key是否存在
        /// 
        public static bool Exists(string key)
        {
            return cache.Exists(key);
        }

    }
}

 

你可能感兴趣的:(asp.net,mvc)