1. 程式人生 > >c#使用 NServiceKit.Redis 封裝 RedisHelper

c#使用 NServiceKit.Redis 封裝 RedisHelper

pub expire private ins scl using load() edi time

在說StackExchange.Redis 的時候說了,因為我們的項目一直.net4.0不升級,沒有辦法,我說的不算,哈哈,又查了StackExchange.Redis在.net4.0使用麻煩,所以選了NServiceKit.Redis。結構也不說了,直接上代碼了。

ICache.cs

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

namespace ClassLibrary2
{
    public interface
ICache { object Get(string key); T GetT<T>(string key) where T : class; object GetWithDelete(string key); T GetWithDelete<T>(string key) where T : class; bool Set(string key, object value); bool Set(string key, object value, DateTime expireDate);
bool SetT<T>(string key, T value) where T : class; bool SetT<T>(string key, T value, DateTime expire) where T : class; bool Remove(string key); } }

Redis.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using NServiceKit.Redis;
using NServiceKit.Redis.Support; namespace ClassLibrary2 { public class Redis : ICache, IDisposable { /// <summary> /// redis客戶端連接池信息 /// </summary> private PooledRedisClientManager prcm; public Redis() { CreateManager(); } /// <summary> /// 創建鏈接池管理對象 /// </summary> private void CreateManager() { try { // ip1:端口1,ip2:端口2 var serverlist = ConfigurationManager.AppSettings["RedisServer"].Split(,); prcm = new PooledRedisClientManager(serverlist, serverlist, new RedisClientManagerConfig { MaxWritePoolSize = 32, MaxReadPoolSize = 32, AutoStart = true }); // prcm.Start(); } catch (Exception e) { #if DEBUG throw; #endif } } /// <summary> /// 客戶端緩存操作對象 /// </summary> public IRedisClient GetClient() { if (prcm == null) CreateManager(); return prcm.GetClient(); } /// <summary> /// 刪除 /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(string key) { using (var client = prcm.GetClient()) { return client.Remove(key); } } /// <summary> /// 獲取 /// </summary> /// <param name="key"></param> /// <returns></returns> public object Get(string key) { using (var client = prcm.GetClient()) { var bytes = client.Get<byte[]>(key); var obj = new ObjectSerializer().Deserialize(bytes); return obj; } } /// <summary> /// 獲取 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T GetT<T>(string key) where T : class { //return Get(key) as T; using (var client = prcm.GetClient()) { return client.Get<T>(key); } } /// <summary> /// 獲取到值到內存中,在刪除 /// </summary> /// <param name="key"></param> /// <returns></returns> public object GetWithDelete(string key) { var result = Get(key); if (result != null) Remove(key); return result; } /// <summary> /// 獲取到值到內存中,在刪除 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T GetWithDelete<T>(string key) where T : class { var result = GetT<T>(key); if (result != null) Remove(key); return result; } /// <summary> ////// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool Set(string key, object value) { using (var client = prcm.GetClient()) { if (client.ContainsKey(key)) { return client.Set<byte[]>(key, new ObjectSerializer().Serialize(value)); } else { return client.Add<byte[]>(key, new ObjectSerializer().Serialize(value)); } } } /// <summary> ////// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expireTime"></param> /// <returns></returns> public bool Set(string key, object value, DateTime expireTime) { using (var client = prcm.GetClient()) { if (client.ContainsKey(key)) { return client.Set<byte[]>(key, new ObjectSerializer().Serialize(value), expireTime); } else { return client.Add<byte[]>(key, new ObjectSerializer().Serialize(value), expireTime); } } } /// <summary> ////// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expire"></param> /// <returns></returns> public bool SetT<T>(string key, T value, DateTime expire) where T : class { try { using (var client = prcm.GetClient()) { return client.Set<T>(key, value, expire); } } catch { return false; } } /// <summary> ////// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool SetT<T>(string key, T value) where T : class { try { using (var client = prcm.GetClient()) { return client.Set<T>(key, value); } } catch { return false; } } public void Dispose() { Close(); } public void Close() { var client = prcm.GetClient(); prcm.Dispose(); } } }

Cache.cs

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

namespace ClassLibrary2
{
    public static class Cache
    {
        private static object cacheLocker = new object();//緩存鎖對象
        private static ICache cache = null;//緩存接口

        static Cache()
        {
            Load();
        }

        /// <summary>
        /// 加載緩存
        /// </summary>
        /// <exception cref=""></exception>
        private static void Load()
        {
            try
            {
                cache = new Redis();
            }
            catch (Exception ex)
            {
                //Log.Error(ex.Message);
            }
        }

        public static ICache GetCache()
        {
            return cache;
        }

        /// <summary>
        /// 獲得指定鍵的緩存值
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <returns>緩存值</returns>
        public static object Get(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                return null;
            return cache.Get(key);
        }

        /// <summary>
        /// 獲得指定鍵的緩存值
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <returns>緩存值</returns>
        public static T GetT<T>(string key) where T : class
        {
            return cache.GetT<T>(key);
        }

        /// <summary>
        /// 將指定鍵的對象添加到緩存中
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <param name="data">緩存值</param>
        public static void Insert(string key, object data)
        {
            if (string.IsNullOrWhiteSpace(key) || data == null)
                return;
            //lock (cacheLocker)
            {
                cache.Set(key, data);
            }
        }
        /// <summary>
        /// 將指定鍵的對象添加到緩存中
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <param name="data">緩存值</param>
        public static void InsertT<T>(string key, T data) where T : class
        {
            if (string.IsNullOrWhiteSpace(key) || data == null)
                return;
            //lock (cacheLocker)
            {
                cache.SetT<T>(key, data);
            }
        }
        /// <summary>
        /// 將指定鍵的對象添加到緩存中,並指定過期時間
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <param name="data">緩存值</param>
        /// <param name="cacheTime">緩存過期時間(分鐘)</param>
        public static void Insert(string key, object data, int cacheTime)
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.Set(key, data, DateTime.Now.AddMinutes(cacheTime));
                }
            }
        }

        /// <summary>
        /// 將指定鍵的對象添加到緩存中,並指定過期時間
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <param name="data">緩存值</param>
        /// <param name="cacheTime">緩存過期時間(分鐘)</param>
        public static void InsertT<T>(string key, T data, int cacheTime) where T : class
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.SetT<T>(key, data, DateTime.Now.AddMinutes(cacheTime));
                }
            }
        }

        /// <summary>
        /// 將指定鍵的對象添加到緩存中,並指定過期時間
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <param name="data">緩存值</param>
        /// <param name="cacheTime">緩存過期時間</param>
        public static void Insert(string key, object data, DateTime cacheTime)
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.Set(key, data, cacheTime);
                }
            }
        }

        /// <summary>
        /// 將指定鍵的對象添加到緩存中,並指定過期時間
        /// </summary>
        /// <param name="key">緩存鍵</param>
        /// <param name="data">緩存值</param>
        /// <param name="cacheTime">緩存過期時間</param>
        public static void InsertT<T>(string key, T data, DateTime cacheTime) where T : class
        {
            if (!string.IsNullOrWhiteSpace(key) && data != null)
            {
                //lock (cacheLocker)
                {
                    cache.SetT<T>(key, data, cacheTime);
                }
            }
        }

        /// <summary>
        /// 從緩存中移除指定鍵的緩存值
        /// </summary>
        /// <param name="key">緩存鍵</param>
        public static void Remove(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                return;
            lock (cacheLocker)
            {
                cache.Remove(key);
            }
        }
    }
}

下載代碼

c#使用 NServiceKit.Redis 封裝 RedisHelper