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 = ,
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的更多相关文章
- c#使用 StackExchange.Redis 封装 RedisHelper
公司一直在用.net自带的缓存,大家都知道.net自带缓存的缺点,就不多说了,不知道的可以查一查,领导最近在说分布式缓存,我们选的是redis,领导让我不忙的时候封装一下,搜索了两天,选了选第三方的插 ...
- [C#] 使用 StackExchange.Redis 封装属于自己的 RedisHelper
使用 StackExchange.Redis 封装属于自己的 RedisHelper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List ...
- [C#] 使用 StackExchange.Redis 封装属于自己的 Helper
使用 StackExchange.Redis 封装属于自己的 Helper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集 ...
- 使用 StackExchange.Redis 封装属于自己的 RedisHelper
目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集合(sorted set) Key 操作 发布订阅 其他 简介 目前 .NE ...
- StackExchange.Redis 封装
博主最近开始玩Redis啊~~ 看了很多Redis的文章,感觉有点云里雾里的,之前看到是ServiceStack.Redis,看了一些大佬封装的Helper类,还是懵懵的QAQ 没办法啊只能硬着**上 ...
- 功能比较全的StackExchange.Redis封装帮助类(.Net/C#)
Redis官网https://redis.io/ 以下内容未全部验证,如有问题请指出 //static NewtonsoftSerializer serializer = new Newtonsoft ...
- PHP 操作redis 封装的类 转的
<?php/** * Redis 操作,支持 Master/Slave 的负载集群 * * @author jackluo */class RedisCluster{ // ...
- Redis封装之List
/// <summary> /// Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销, /// Redis内部的很多实现,包括发 ...
- Redis封装之String
RedisBase类 /// <summary> /// RedisBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存 /// </summary ...
随机推荐
- Springboot 使用Jwt token失效时接口无响应(乌龙)
问题背景:新项目使用Springboot框架,鉴权使用了Jwt 处理cors: @Configuration public class WebMvcConfig implements WebMvcCo ...
- 【转帖】PostgreSQL之 使用扩展Extension
PostgreSQL之 使用扩展Extension https://www.cnblogs.com/lnlvinso/p/11042677.html 挺好的文章.自己之前没有系统学习过 扩展.. 目前 ...
- MySQL函数和过程(三)
--加密32位字符select md5('123456') --获取字符串的长度(一个中文三个长度)select LENGTH('呵呵') --获取字符串字符个数select CHAR_LENGTH( ...
- ubuntu 忘记密码如何 修改密码
ubuntu 忘记密码如何 修改密码 这个链接讲的很不错 https://blog.csdn.net/zd147896325/article/details/81664558 本来我只是玩一玩,但是我 ...
- 10.使用du将文件按大小进行排序
按G进行排序du -sh * | grep G | sort -nr
- decimal, double, float
更新: 2019-09-08 c# and js 要 ceil floor 2 decimal point 都没有 build in 的 solution 比如 15.667 想 ceil to ...
- linux脚本监控应用且通过邮件报警异常
一.背景 最近接到监控应用并通过邮件报警的任务,由于需求比较简单,故没有使用springboot那套,而是采用linux脚本的方式进行监控. 二.思路 通过linux自带的定时功能,定时执行一个lin ...
- jQuery 手写菜单(ing)
菜单支持多级 直接上代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...
- 日志(logging)与正则(re)模块
logging模块 #日志:日常的流水 =>日志文件,将程序运行过程中的状态或数据进行记录,一般都是记录到日志文件中 #1.logging模块一共分为五个打印级别 debug.info.warn ...
- GC原理图
GC原理图,Jdk1.6及以下版本 永久代 永久代是Hotspot虚拟机特有的概念,是方法区的一种实现,别的JVM都没有这个东西.在Java 8中,永久代被彻底移除,取而代之的是另一块与堆不相连的本地 ...