在说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 = ,
MaxReadPoolSize = ,
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的更多相关文章

  1. c#使用 StackExchange.Redis 封装 RedisHelper

    公司一直在用.net自带的缓存,大家都知道.net自带缓存的缺点,就不多说了,不知道的可以查一查,领导最近在说分布式缓存,我们选的是redis,领导让我不忙的时候封装一下,搜索了两天,选了选第三方的插 ...

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

    使用 StackExchange.Redis 封装属于自己的 RedisHelper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List ...

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

    使用 StackExchange.Redis 封装属于自己的 Helper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集 ...

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

    目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集合(sorted set) Key 操作 发布订阅 其他 简介 目前 .NE ...

  5. StackExchange.Redis 封装

    博主最近开始玩Redis啊~~ 看了很多Redis的文章,感觉有点云里雾里的,之前看到是ServiceStack.Redis,看了一些大佬封装的Helper类,还是懵懵的QAQ 没办法啊只能硬着**上 ...

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

    Redis官网https://redis.io/ 以下内容未全部验证,如有问题请指出 //static NewtonsoftSerializer serializer = new Newtonsoft ...

  7. PHP 操作redis 封装的类 转的

    <?php/** * Redis 操作,支持 Master/Slave 的负载集群 * * @author jackluo */class RedisCluster{           // ...

  8. Redis封装之List

    /// <summary> /// Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销, /// Redis内部的很多实现,包括发 ...

  9. Redis封装之String

    RedisBase类 /// <summary> /// RedisBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存 /// </summary ...

随机推荐

  1. 磁盘冗余列阵Raid技术知识与实践

    Raid介绍 什么是Raid?  Raid级别介绍  Raid 技术分类 RAID分为两类: 软RAID, 系统层面实现的,性能差. 硬RAID, 硬件层面实现的,性能好. 主板板载RAID: 功能弱 ...

  2. Reactor系列(十一)take获取

    #java#reactor#take#获取# 获取Flux订阅数量 视频讲解: https://www.bilibili.com/video/av80322616/ FluxMonoTestCase. ...

  3. Reactor系列(六)Exception异常系列(六)Exception异常

    #java##reactor##flux##error##exception# 视频解说: https://www.bilibili.com/video/av79468713/ FluxMonoTes ...

  4. shell中得到当下路径所有文件夹名称

      方法1: for dir in $(ls -al ./|awk '/^d/ {print $NF}') do echo $dir done   方法2: for dir in $(ls ./) d ...

  5. Design Compressed String Iterator

    Design and implement a data structure for a compressed string iterator. It should support the follow ...

  6. [转帖]Intel 上一代 可扩展CPU的简单报价

    8.1万元人间毒物!Intel 28核铂金版Xeon 8180零售上市 http://news.mydrivers.com/1/541/541670.htm 猜你想看:英特尔 CPU处理器 Xeon ...

  7. C++ Primer 5th Chap1.Getting Started

    在CommandPrompt上:(即cmd) 假定文件名为prog1.cc: 编译:$Compiler'sName prog1.cc 打开(prog1.exe):$prog1 打开(在当前目录):$. ...

  8. Exchanging Gifts--2019CCPC哈尔滨 E题

    题意:http://codeforces.com/gym/102394/problem/E 1操作是给你一串数,2操作是连结两个串(所以可能很长),问你最后一个串的值(知道最多的个数就很好算,关键计算 ...

  9. 洛谷P1087 FBI树

    P1087 FBI树题解: 看到这个题,我想到了线段树!(毕竟刚搞完st表...) 当然,题解中有位大佬也用的线段树,但是当时看的时候我看见了9个if,当场去世. 那么这是一个不用暴力的线段树,且简单 ...

  10. Sql Server 分区演练

    USE [master] GO if exists (select * from sys.databases where name = 'Test_1') drop database Test_1 G ...