使用redis组件如下,至于为什么使用3.9版本,是因为4.0开始商业了,限制了次数
ServiceStack.Common" version="3.9.70"
ServiceStack.Redis" version="3.9.71"
ServiceStack.Text" version="3.9.71"
接口
public interface ICache { #region Key-Value ////// 读取缓存 /// /// 键 /// T Read (string cacheKey, long dbId = 0) where T : class; /// /// 写入缓存 /// /// 对象数据 /// 键 void Write (string cacheKey, T value, long dbId = 0) where T : class; /// /// 写入缓存 /// /// 对象数据 /// 键 /// 到期时间 void Write (string cacheKey, T value, DateTime expireTime, long dbId = 0) where T : class; /// /// 写入缓存 /// /// 对象数据 /// 键 /// 到期时间 void Write (string cacheKey, T value, TimeSpan timeSpan, long dbId = 0) where T : class; /// /// 移除指定数据缓存 /// /// 键 void Remove(string cacheKey, long dbId = 0); /// /// 移除全部缓存 /// void RemoveAll(long dbId = 0); #endregion }
配置类
public sealed class RedisConfigInfo : ConfigurationSection { ////// 获取配置信息 /// /// public static RedisConfigInfo GetConfig() { return GetConfig("redisconfig"); } /// /// 获取配置信息 /// /// xml节点名称 /// public static RedisConfigInfo GetConfig(string sectionName) { RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection(sectionName); if (section == null) throw new ConfigurationErrorsException("Section " + sectionName + " is not found."); return section; } /// /// 可写的Redis链接地址 /// [ConfigurationProperty("WriteServerList", IsRequired = false)] public string WriteServerList { get { return (string)base["WriteServerList"]; } set { base["WriteServerList"] = value; } } /// /// 可读的Redis链接地址 /// [ConfigurationProperty("ReadServerList", IsRequired = false)] public string ReadServerList { get { return (string)base["ReadServerList"]; } set { base["ReadServerList"] = value; } } /// /// 最大写链接数 /// [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)] public int MaxWritePoolSize { get { int _maxWritePoolSize = (int)base["MaxWritePoolSize"]; return _maxWritePoolSize > 0 ? _maxWritePoolSize : 5; } set { base["MaxWritePoolSize"] = value; } } /// /// 最大读链接数 /// [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)] public int MaxReadPoolSize { get { int _maxReadPoolSize = (int)base["MaxReadPoolSize"]; return _maxReadPoolSize > 0 ? _maxReadPoolSize : 5; } set { base["MaxReadPoolSize"] = value; } } /// /// 自动重启 /// [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)] public bool AutoStart { get { return (bool)base["AutoStart"]; } set { base["AutoStart"] = value; } } /// /// 本地缓存到期时间,单位:秒 /// [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)] public int LocalCacheTime { get { return (int)base["LocalCacheTime"]; } set { base["LocalCacheTime"] = value; } } /// /// 是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项 /// [ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)] public bool RecordeLog { get { return (bool)base["RecordeLog"]; } set { base["RecordeLog"] = value; } } /// /// 默认开始db /// [ConfigurationProperty("DefaultDb", IsRequired = false)] public long DefaultDb { get { return (long)base["DefaultDb"]; } set { base["DefaultDb"] = value; } } }
处理类
public class RedisCache { #region -- 连接信息 -- ////// redis配置文件信息 /// private static RedisConfigInfo redisConfigInfo = RedisConfigInfo.GetConfig(); /// /// 创建链接池管理对象 /// private static PooledRedisClientManager CreateManager(long dbId) { string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ","); string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ","); return new PooledRedisClientManager(readServerList, writeServerList, new RedisClientManagerConfig { MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize, MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize, AutoStart = redisConfigInfo.AutoStart, DefaultDb = dbId }); } /// /// 字串转数组 /// /// 字串 /// 分隔符 /// private static string[] SplitString(string strSource, string split) { return strSource.Split(split.ToArray()); } /// /// 获取redis客户端根据库ID号 /// /// redis库Id /// private static PooledRedisClientManager GetClientManager(long dbId) { return CreateManager(dbId); } #endregion #region -- Item -- /// /// 设置单体 /// /// 值类型 /// 键值 /// 值 /// 库Id /// public static bool Set (string key, T t, long dbId = 0) { var clientManager = GetClientManager(dbId); IRedisClient redis = clientManager.GetClient(); var res = redis.Set (key, t); clientManager.DisposeClient((RedisNativeClient)redis); redis.Dispose(); clientManager.Dispose(); return res; } /// /// 设置单体 /// /// 值类型 /// 键值 /// 值 /// 保存时间 /// 库Id /// public static bool Set (string key, T t, TimeSpan timeSpan, long dbId = 0) { var clientManager = GetClientManager(dbId); IRedisClient redis = clientManager.GetClient(); var res = redis.Set (key, t, timeSpan); clientManager.DisposeClient((RedisNativeClient)redis); redis.Dispose(); clientManager.Dispose(); return res; } /// /// 设置单体 /// /// 值类型 /// 键值 /// 值 /// 过期时间 /// public static bool Set (string key, T t, DateTime dateTime, long dbId = 0) { var clientManager = GetClientManager(dbId); IRedisClient redis = clientManager.GetClient(); var res = redis.Set (key, t, dateTime); clientManager.DisposeClient((RedisNativeClient)redis); redis.Dispose(); clientManager.Dispose(); return res; } /// /// 获取单体 /// /// 值类型 /// 键值 /// public static T Get (string key, long dbId = 0) where T : class { var clientManager = GetClientManager(dbId); IRedisClient redis = clientManager.GetClient(); var res = redis.Get (key); clientManager.DisposeClient((RedisNativeClient)redis); redis.Dispose(); clientManager.Dispose(); return res; } /// /// 移除单体 /// /// 键值 public static bool Remove(string key, long dbId = 0) { var clientManager = GetClientManager(dbId); IRedisClient redis = clientManager.GetClient(); var res = redis.Remove(key); clientManager.DisposeClient((RedisNativeClient)redis); redis.Dispose(); clientManager.Dispose(); return res; } /// /// 清空所有缓存 /// public static void RemoveAll(long dbId = 0) { var clientManager = GetClientManager(dbId); IRedisClient redis = clientManager.GetClient(); redis.FlushDb(); clientManager.DisposeClient((RedisNativeClient)redis); redis.Dispose(); clientManager.Dispose(); } #endregion #region -- List -- /// /// 添加列表 /// /// 类型 /// 键值 /// 值 /// 库 public static void List_Add (string key, T t, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var redisTypedClient = redis.As (); redisTypedClient.AddItemToList(redisTypedClient.Lists[key], t); } } /// /// 移除列表某个值 /// /// 类型 /// 键值 /// 值 /// 库 /// public static bool List_Remove (string key, T t, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var redisTypedClient = redis.As (); return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0; } } /// /// 移除列表所有值 /// /// 类型 /// 键值 /// 库Id public static void List_RemoveAll (string key, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var redisTypedClient = redis.As (); redisTypedClient.Lists[key].RemoveAll(); } } /// /// 获取列表数据条数 /// /// /// /// public static long List_Count(string key, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { return redis.GetListCount(key); } } /// /// 获取指定条数列表数据 /// /// 类型 /// 键值 /// 开始编号 /// 条数 /// 库 /// public static List List_GetRange (string key, int start, int count, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var c = redis.As (); return c.Lists[key].GetRange(start, start + count - 1); } } /// /// 获取列表所有数据 /// /// 类型 /// 键值 /// 库数据 /// public static List List_GetList (string key, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var c = redis.As (); return c.Lists[key].GetRange(0, c.Lists[key].Count); } } /// /// 获取列表分页数据 /// /// 类型 /// 键值 /// 页码 /// 每页条数 /// 库 /// public static List List_GetList (string key, int pageIndex, int pageSize, long dbId = 0) { int start = pageSize * (pageIndex - 1); return List_GetRange (key, start, pageSize, dbId); } #endregion #region -- Set -- /// /// 添加集合 /// /// 类型 /// 键值 /// 数值 /// 库 public static void Set_Add (string key, T t, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var redisTypedClient = redis.As (); redisTypedClient.Sets[key].Add(t); } } /// /// 集合是否包含指定数据 /// /// 类型 /// 键值 /// 数值 /// 库 /// public static bool Set_Contains (string key, T t, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var redisTypedClient = redis.As (); return redisTypedClient.Sets[key].Contains(t); } } /// /// 移除集合某个值 /// /// 类型 /// 键值 /// 数值 /// 库 /// public static bool Set_Remove (string key, T t, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var redisTypedClient = redis.As (); return redisTypedClient.Sets[key].Remove(t); } } #endregion #region -- Hash -- /// /// 判断某个数据是否已经被缓存 /// /// 类型 /// hashID /// 键值 /// 库 /// public static bool Hash_Exist (string key, string dataKey, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { return redis.HashContainsEntry(key, dataKey); } } /// /// 存储数据到hash表 /// /// 类型 /// hashID /// 键值 /// 数值 /// 库 /// public static bool Hash_Set (string key, string dataKey, T t, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { string value = ServiceStack.Text.JsonSerializer.SerializeToString (t); return redis.SetEntryInHash(key, dataKey, value); } } /// /// 移除hash中的某值 /// /// hashID /// 键值 /// 库 /// public static bool Hash_Remove(string key, string dataKey, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { return redis.RemoveEntryFromHash(key, dataKey); } } /// /// 移除整个hash /// /// hashID /// 库 /// public static bool Hash_Remove(string key, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { return redis.Remove(key); } } /// /// 从hash表获取数据 /// /// 类型 /// hashID /// 键值 /// 库 /// public static T Hash_Get (string key, string dataKey, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { string value = redis.GetValueFromHash(key, dataKey); return ServiceStack.Text.JsonSerializer.DeserializeFromString (value); } } /// /// 获取整个hash的数据 /// /// 类型 /// hashID /// 库 /// public static List Hash_GetAll (string key, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var list = redis.GetHashValues(key); if (list != null && list.Count > 0) { List result = new List (); foreach (var item in list) { var value = ServiceStack.Text.JsonSerializer.DeserializeFromString (item); result.Add(value); } return result; } return null; } } #endregion #region -- SortedSet -- /// /// 添加数据到 SortedSet /// /// 类型 /// 集合id /// 数值 /// 排序码 /// 库 public static bool SortedSet_Add (string key, T t, double score, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { string value = ServiceStack.Text.JsonSerializer.SerializeToString (t); return redis.AddItemToSortedSet(key, value, score); } } /// /// 移除数据从SortedSet /// /// 类型 /// 集合id /// 数值 /// 库 /// public static bool SortedSet_Remove (string key, T t, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { string value = ServiceStack.Text.JsonSerializer.SerializeToString (t); return redis.RemoveItemFromSortedSet(key, value); } } /// /// 修剪SortedSet /// /// 键值 /// 保留的条数 /// 库 /// public static long SortedSet_Trim(string key, int size, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { return redis.RemoveRangeFromSortedSet(key, size, 9999999); } } /// /// 获取SortedSet的长度 /// /// 键值 /// 库 /// public static long SortedSet_Count(string key, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { return redis.GetSortedSetCount(key); } } /// /// 获取SortedSet的分页数据 /// /// 类型 /// 键值 /// 页码 /// 每页条数 /// 库 /// public static List SortedSet_GetList (string key, int pageIndex, int pageSize, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var list = redis.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1); if (list != null && list.Count > 0) { List result = new List (); foreach (var item in list) { var data = ServiceStack.Text.JsonSerializer.DeserializeFromString (item); result.Add(data); } return result; } } return null; } /// /// 获取SortedSet的全部数据 /// /// 类 /// 键值 /// 库 /// public static List SortedSet_GetListALL (string key, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { var list = redis.GetRangeFromSortedSet(key, 0, 9999999); if (list != null && list.Count > 0) { List result = new List (); foreach (var item in list) { var data = ServiceStack.Text.JsonSerializer.DeserializeFromString (item); result.Add(data); } return result; } } return null; } #endregion #region 公用方法 /// /// 设置缓存过期 /// /// 键值 /// 过期时间 /// 库 public static void SetExpire(string key, DateTime datetime, long dbId = 0) { using (IRedisClient redis = CreateManager(dbId).GetClient()) { redis.ExpireEntryAt(key, datetime); } } #endregion }
接口实现
public class CacheByRedis : ICache { #region Key-Value ////// 读取缓存 /// /// 键 /// public T Read (string cacheKey, long dbId = 0) where T : class { return RedisCache.Get (RedisPrev + cacheKey, dbId); } /// /// 写入缓存 /// /// 对象数据 /// 键 public void Write (string cacheKey, T value, long dbId = 0) where T : class { RedisCache.Set(RedisPrev + cacheKey, value, dbId); } /// /// 写入缓存 /// /// 对象数据 /// 键 /// 到期时间 public void Write (string cacheKey, T value, DateTime expireTime, long dbId = 0) where T : class { RedisCache.Set(RedisPrev + cacheKey, value, expireTime, dbId); } /// /// 写入缓存 /// /// 对象数据 /// 键 /// 缓存时间 public void Write (string cacheKey, T value, TimeSpan timeSpan, long dbId = 0) where T : class { RedisCache.Set(RedisPrev + cacheKey, value, timeSpan, dbId); } /// /// 移除指定数据缓存 /// /// 键 public void Remove(string cacheKey, long dbId = 0) { RedisCache.Remove(RedisPrev + cacheKey, dbId); } /// /// 移除全部缓存 /// public void RemoveAll(long dbId = 0) { RedisCache.RemoveAll(dbId); } /// /// 缓存前缀 /// private static string _RedisPrev = ""; private string RedisPrev { get { if (_RedisPrev.Length == 0) _RedisPrev = ConfigurationManager.AppSettings["RedisPrev"].ToString(); return _RedisPrev; } } #endregion }
然后再弄个小工厂妥妥的
public static ICache CaChe() { return new CacheByRedis(); }
代码到此结束,使用的话自己慢慢玩