我希望有一个缓存类来缓存不同的类型。我希望每种类型都在不同的MemoryCache中缓存,但要以一种通用的方式缓存。
我做得对吗?
internal static class RecordsCache
{
private static Dictionary<string, ObjectCache> cacheStore;
static private CacheItemPolicy policy = null;
static RecordsCache()
{
cacheStore = new Dictionary<string, ObjectCache>();
ObjectCache activitiesCache = new MemoryCache(typeof(Activity).ToString());
ObjectCache lettersCache = new MemoryCache(typeof(Letter).ToString());
ObjectCache contactssCache = new MemoryCache(typeof(Contact).ToString());
cacheStore.Add(typeof(Activity).ToString(), activitiesCache);
cacheStore.Add(typeof(Letter).ToString(), lettersCache );
cacheStore.Add(typeof(Contact).ToString(), contactssCache );
policy = new CacheItemPolicy();
policy.Priority = CacheItemPriority.Default;
policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(12);
}
public static void Set<T>(string userID, int year, List<T> records)
{
var cache = cacheStore[typeof(T).ToString()];
string key = userID + "-" + year.ToString();
cache.Set(key, records, policy);
}
public static bool TryGet<T>(string userID, int year, out List<T> records)
{
var cache = cacheStore[typeof(T).ToString()];
string key = userID + "-" + year.ToString();
records = cache[key] as List<T>;
return records != null;
}
public static void Remove<T>(string userID, int year)
{
var cache = cacheStore[typeof(T).ToString()];
string key = userID + "-" + year.ToString();
cache.Remove(key);
}
}发布于 2014-03-01 08:01:26
typeof(T).ToString()。BuildKey(string userId, int year)方法中。这意味着,如果您需要更改键的构建方式,您只需要触摸一个方法,而不是所有的方法。Register方法,它接受要为其创建新缓存的类型,而不是硬编码它。发布于 2014-03-01 07:28:08
在我看来,每件事都有很好的编码。
这里只是一些个人偏好:
Set<T>方法,它接受一个函数作为输入,而不是List<T>:公共静态空集(string userId,int,Func> retrieveData) {}Get和Set组合在一起,看起来是: public List TryGetAndSet(string userId,int retrieveData,Func> retrieveData) { //如果缓存项存在返回cacheItem //如果缓存项不存在,则通过执行retrieveData//如果检索到的结果,设置为缓存并返回结果}来检索数据。https://codereview.stackexchange.com/questions/43111
复制相似问题