Redis作为缓存服务器

时间:2024-01-05 11:13:44

  1、ICache的Redis实现没有放在'Framework.Cache/Logic'中。如果是以前,我会认为这样不好。我会这样做,'Framework.Cache'项目引用Redis项目或直接从Nuget安装Redis,

把实现定义在‘Framework.Cache/Logic’中,这样结构看起来很顺眼,‘这算是高内聚么!!!’。不过自从接触了IOC后,现在这样的结构似乎也很合理,没什么违和感。

这就好似把‘IRepository’和‘Repositories’,一个放在Domain,一个放在Infrastructure

  2、当前比较稳定的Redis客户端(开源的程序包)有ServiceStack.Redis 和 StackExchange.Redis。我都用了一下,ServiceStatck的

比较好用,不过我感觉后者的性能应该会稍好点

  3、关于ServiceStack.Redis中的接口,IRedisClient,ICacheClient,IRedisTypedClient<T>,IEntityStore<T>,IEntityStore。

这些“乱七八糟”的接口和CRUD都有关系,中的有些方法看似好像是重复的,后续希望能整理出一篇结合源码,理论点的文章

  Redis作为缓存服务器

一、Framework.Cache

接口ICache,定义缓存操作开放的方法

     public interface ICache
{
/// <summary>
/// Gets all entries in the cache
/// </summary>
IEnumerable<KeyValuePair<string, object>> Entries { get; } /// <summary>
/// Gets a cache item associated with the specified key or adds the item
/// if it doesn't exist in the cache.
/// </summary>
/// <typeparam name="T">The type of the item to get or add</typeparam>
/// <param name="key">The cache item key</param>
/// <param name="baseMethod">Func which returns value to be added to the cache</param>
/// <returns>Cached item value</returns>
T Get<T>(string key, Func<T> baseMethod); /// <summary>
/// Gets a cache item associated with the specified key or adds the item
/// if it doesn't exist in the cache.
/// </summary>
/// <typeparam name="T">The type of the item to get or add</typeparam>
/// <param name="key">The cache item key</param>
/// <param name="baseMethod">Func which returns value to be added to the cache</param>
/// <param name="cacheTime">Expiration time in minutes</param>
/// <returns>Cached item value</returns>
T Get<T>(string key, Func<T> baseMethod, int cacheTime); /// <summary>
/// Gets a value indicating whether an item associated with the specified key exists in the cache
/// </summary>
/// <param name="key">key</param>
/// <returns>Result</returns>
bool Contains(string key); /// <summary>
/// Removes the value with the specified key from the cache
/// </summary>
/// <param name="key">/key</param>
void Remove(string key);
}

二、基于‘ServiceStack.Redis’的缓存实现

 public class SSRedisCache : ICache
{
private const string REGION_NAME = "$#SSRedisCache#$";
private const int _DefaultCacheTime = ;
private readonly static object s_lock = new object(); private IRedisClient GetClient()
{
return RedisManager.GetClient();
} private IRedisClient GetReadOnlyClient()
{
return RedisManager.GetReadOnlyClient();
} public IEnumerable<KeyValuePair<string, object>> Entries
{
get { throw new NotImplementedException(); }
} public T Get<T>(string key, Func<T> baseMethod)
{
return Get<T>(key, baseMethod, _DefaultCacheTime);
} public T Get<T>(string key, Func<T> baseMethod, int cacheTime)
{
using (var redisClient = GetClient())
{
key = BuildKey(key); if (redisClient.ContainsKey(key))
{
return redisClient.Get<T>(key);
}
else
{
lock (s_lock)
{
if (!redisClient.ContainsKey(key))
{
var value = baseMethod();
if (value != null) //请区别null与String.Empty
{
redisClient.Set<T>(key, value, TimeSpan.FromMinutes(cacheTime));
//redisClient.Save();
}
return value;
}
return redisClient.Get<T>(key);
}
}
}
} public bool Contains(string key)
{
using (var redisClient = GetReadOnlyClient())
{
return redisClient.ContainsKey(BuildKey(key));
}
} public void Remove(string key)
{
using (var redisClient = GetClient())
{
redisClient.Remove(BuildKey(key));
}
} private string BuildKey(string key)
{
return string.IsNullOrEmpty(key) ? null : REGION_NAME + key;
} }

三、基于‘StackExchange.Redis’的缓存实现

 <?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MsgPack.Cli" version="0.6.8" targetFramework="net45" />
<package id="StackExchange.Redis" version="1.0.488" targetFramework="net45" />
<package id="StackExchange.Redis.Extensions.Core" version="1.3.2.0" targetFramework="net45" />
<package id="StackExchange.Redis.Extensions.MsgPack" version="1.3.2.0" targetFramework="net45" />
</packages>
 public class SERedisCache : ICache
{
private const string REGION_NAME = "$#SERedisCache#$";
private const int _DefaultCacheTime = ;
private readonly static object s_lock = new object(); private StackExchangeRedisCacheClient GetClient()
{
return new StackExchangeRedisCacheClient(RedisServer.Connection, new MsgPackObjectSerializer());
} public IEnumerable<KeyValuePair<string, object>> Entries
{
get { throw new NotImplementedException(); }
} public T Get<T>(string key, Func<T> baseMethod)
{
return Get(key, baseMethod, _DefaultCacheTime);
} public T Get<T>(string key, Func<T> baseMethod, int cacheTime)
{
using (var cacheClient = GetClient())
{
key = BuildKey(key); if (cacheClient.Exists(key))
{
return cacheClient.Get<T>(key);
}
else
{
lock (s_lock)
{
if (!cacheClient.Exists(key))
{
var value = baseMethod();
if (value != null) //请区别null与String.Empty
{
cacheClient.Add<T>(key, value, TimeSpan.FromMinutes(cacheTime));
}
return value;
}
return cacheClient.Get<T>(key);
}
}
}
} public bool Contains(string key)
{
using (var cacheClient = GetClient())
{
return cacheClient.Exists(BuildKey(key));
}
} public void Remove(string key)
{
using (var cacheClient = GetClient())
{
cacheClient.Remove(BuildKey(key));
}
} private string BuildKey(string key)
{
return string.IsNullOrEmpty(key) ? null : REGION_NAME + key;
} }

完整代码(稍后) 会在另一篇文章关于Web API中附上