c#使用 NServiceKit.Redis 封装 RedisHelper

在说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);
            }
        }
    }
}

下载代码

时间: 2024-09-30 04:43:25

c#使用 NServiceKit.Redis 封装 RedisHelper的相关文章

[C#] 使用 StackExchange.Redis 封装属于自己的 RedisHelper

使用 StackExchange.Redis 封装属于自己的 RedisHelper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集合(sorted set) Key 操作 发布订阅 其他 简介 目前 .NET 使用访问 Redis 的的类库主流应该是 StackExchange.Redis,自己参考网上的文章(也许是吃饱了撑着),也尝试做出简单的封装. #region using System; using Syst

使用 StackExchange.Redis 封装属于自己的 RedisHelper

目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集合(sorted set) Key 操作 发布订阅 其他 简介 目前 .NET 使用访问 Redis 的的类库主流应该是 StackExchange.redis,自己参考网上的文章(也许是吃饱了撑着),也尝试做出简单的封装. /// <summary> /// Redis 助手 /// </summary> public class RedisHelper {

java- 简单redis 封装

jedis 简单使用并不复杂,但是考虑到效率问题,还是需要用到 jedispool,简单封装一下,方便调用,mark 一下. 1.由于没有封装自己的序列化接口,所以这块需要我们自己实现 1 package com.lixiaodao.common.redis; 2 3 public interface Serializer<T> { 4 5 String serialize(T value); 6 7 T deserialize(String value,Class<T> claz

功能比较全的StackExchange.Redis封装帮助类(.Net/C#)

Redis官网https://redis.io/ 以下内容未全部验证,如有问题请指出 //static NewtonsoftSerializer serializer = new NewtonsoftSerializer(); //static StackExchangeRedisCacheClient cacheClient = new StackExchangeRedisCacheClient(serializer); //private static IDatabase db = cach

PHP 操作redis 封装的类

1 <?php 2 /** 3 * Redis 操作,支持 Master/Slave 的负载集群 4 * 6 */ 7 class RedisCluster{ 8 9 // 是否使用 M/S 的读写集群方案 10 private $_isUseCluster = false; 11 12 // Slave 句柄标记 13 private $_sn = 0; 14 15 // 服务器连接句柄 16 private $_linkHandle = array( 17 'master'=>null,/

redis封装 get查询/删除key/key查询

#coding:utf-8 import redisimport msgpack #自己填写地址 class Redis_Mod(): def __init__(self): self.conn = Redis_Mod.__getCon() @staticmethod def __getCon(): try: conn = redis.Redis(host= Redis_DB.Host_R(), port= Redis_DB.Port_R(), password= Redis_DB.Pwd_R(

【redis 封装】

<?php /** * Created by PhpStorm. * User: andy * Date: 18/3/26 */ namespace app\common\lib\redis; class Predis { public $redis = ""; /** * 定义单例模式的变量 * @var null */ private static $_instance = null; public static function getInstance() { if(emp

Redis封装之RedisHashService

RedisHashService: /// <summary> /// Hash:类似dictionary,通过索引快速定位到指定元素的,耗时均等,跟string的区别在于不用反序列化,直接修改某个字段 /// Hash的话,一个hashid-{key:value;key:value;key:value;} /// 可以一次性查找实体,也可以单个,还可以单个修改 /// </summary> public class RedisHashService : RedisBase { #

Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信. Memcached安装和基本使用 Memcached安装: wget http://memcached.org/latest