CacheHelper对缓存的控制
通常我们针对页面以及相关数据进行相应的缓存(分为客户端和服务端的缓存),以下代码为对一般操作进行相应的缓存(服务端),用以减少对数据库的访问次数,减少服务器的压力。
(一)CacheHelper类
CacheHelper类主要是依赖于系统的System.Web.Caching.HostingEnvironment.Cache,具体代码如下:
public static class CacheHelper
{
private static Cache _cache;
public static double SaveTime
{
get;
set;
}
static CacheHelper()
{
_cache = HostingEnvironment.Cache;
SaveTime = 15.0;
}
public static object Get(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
return _cache.Get(key);
}
public static T Get<T>(string key)
{
object obj = Get(key);
return obj==null?default(T):(T)obj;
}
public static void Insert(string key, object value, CacheDependency dependency, CacheItemPriority priority, CacheItemRemovedCallback callback)
{
_cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(SaveTime), priority, callback);
}
public static void Insert(string key, object value, CacheDependency dependency, CacheItemRemovedCallback callback)
{
Insert(key, value, dependency, CacheItemPriority.Default, callback);
}
public static void Insert(string key, object value, CacheDependency dependency)
{
Insert(key, value, dependency, CacheItemPriority.Default, null);
}
public static void Insert(string key, object value)
{
Insert(key, value, null, CacheItemPriority.Default, null);
}
public static void Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return;
}
_cache.Remove(key);
}
public static IList<string> GetKeys()
{
List<string> keys = new List<string>();
IDictionaryEnumerator enumerator = _cache.GetEnumerator();
while (enumerator.MoveNext())
{
keys.Add(enumerator.Key.ToString());
}
return keys.AsReadOnly();
}
public static void RemoveAll()
{
IList<string> keys = GetKeys();
foreach (string key in keys)
{
_cache.Remove(key);
}
}
}
}
{
private static Cache _cache;
public static double SaveTime
{
get;
set;
}
static CacheHelper()
{
_cache = HostingEnvironment.Cache;
SaveTime = 15.0;
}
public static object Get(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
return _cache.Get(key);
}
public static T Get<T>(string key)
{
object obj = Get(key);
return obj==null?default(T):(T)obj;
}
public static void Insert(string key, object value, CacheDependency dependency, CacheItemPriority priority, CacheItemRemovedCallback callback)
{
_cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(SaveTime), priority, callback);
}
public static void Insert(string key, object value, CacheDependency dependency, CacheItemRemovedCallback callback)
{
Insert(key, value, dependency, CacheItemPriority.Default, callback);
}
public static void Insert(string key, object value, CacheDependency dependency)
{
Insert(key, value, dependency, CacheItemPriority.Default, null);
}
public static void Insert(string key, object value)
{
Insert(key, value, null, CacheItemPriority.Default, null);
}
public static void Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return;
}
_cache.Remove(key);
}
public static IList<string> GetKeys()
{
List<string> keys = new List<string>();
IDictionaryEnumerator enumerator = _cache.GetEnumerator();
while (enumerator.MoveNext())
{
keys.Add(enumerator.Key.ToString());
}
return keys.AsReadOnly();
}
public static void RemoveAll()
{
IList<string> keys = GetKeys();
foreach (string key in keys)
{
_cache.Remove(key);
}
}
}
}
在原有基础上增加了如下3个方法:
(1)public static T Get<T>(string key)
(2)public static IList<string> GetKeys()
(3)public static void RemoveAll()
这样我们能够方便的以静态方法来对Cache进行相应的操作。
(二)Cache类
Cache类位于System.Web.Caching命名空间下,实现了IEnumerable接口,主要方法如下:
public sealed class Cache : IEnumerable
{
public object Get(string key);
public IDictionaryEnumerator GetEnumerator();
public void Insert(string key, object value);
public void Insert(string key, object value, CacheDependency dependencies);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
public object Remove(string key);
}
{
public object Get(string key);
public IDictionaryEnumerator GetEnumerator();
public void Insert(string key, object value);
public void Insert(string key, object value, CacheDependency dependencies);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
public object Remove(string key);
}
在底层,应该是以一个字典来对相关的键值对来进行数据保存。
(三)CacheHelper相关的单元测试
[TestClass()]
public class CacheHelperTest
{
/// <summary>
///Get 的测试
///</summary>
[TestMethod()]
public void GetTest()
{
string key = "key";
object actual = CacheHelper.Get(key);
Assert.IsNull(actual);
Cache cache = HostingEnvironment.Cache;
string value="value";
cache.Insert(key,value);
actual = CacheHelper.Get(key);
Assert.IsNotNull(actual);
Assert.IsTrue(actual.ToString()==value);
}
/// <summary>
///Get 的测试
///</summary>
[TestMethod()]
public void GetWithAbnormalParameterTest()
{
object actual = CacheHelper.Get(string.Empty);
Assert.IsNull(actual);
actual = CacheHelper.Get(null);
Assert.IsNull(actual);
}
/// <summary>
///GetKeys 的测试
///</summary>
[TestMethod()]
public void GetKeysTest()
{
int count = (new Random()).Next(10);
IList<string> keys = CreateAllKeys(count);
InsertAllKeys(keys);
IList<string> results = CacheHelper.GetKeys();
Assert.IsTrue(results.Count == count);
for (int index = 0; index < count; index++)
{
Assert.IsTrue(results.Contains(keys[index]));
}
for (int index = 0; index < count; index++)
{
Assert.IsTrue(keys.Contains(results[index]));
}
}
private void InsertAllKeys(IList<string> keys)
{
Cache cache = HostingEnvironment.Cache;
foreach (string key in keys)
{
cache.Insert(key,key);
}
}
private IList<string> CreateAllKeys(int count)
{
IList<string> keys = new List<string>();
for (int index = 0; index < count; index++)
{
keys.Add("KEY"+index.ToString());
}
return keys;
}
/// <summary>
///Remove 的测试
///</summary>
[TestMethod()]
public void RemoveTest()
{
int count = 1;
IList<string> keys = CreateAllKeys(count);
InsertAllKeys(keys);
string key = keys[0];
IList<string> results = CacheHelper.GetKeys();
Assert.IsTrue(results.Contains(key));
CacheHelper.Remove(key);
results = CacheHelper.GetKeys();
Assert.IsFalse(results.Contains(key));
}
/// <summary>
///RemoveAll 的测试
///</summary>
[TestMethod()]
public void RemoveAllTest()
{
int count = (new Random()).Next(20);
IList<string> keys = CreateAllKeys(count);
InsertAllKeys(keys);
IList<string> results = CacheHelper.GetKeys();
foreach (string key in keys)
{
Assert.IsTrue(results.Contains(key));
}
CacheHelper.RemoveAll();
results = CacheHelper.GetKeys();
Assert.IsTrue(results.Count==0);
}
/// <summary>
///SaveTime 的测试
///</summary>
[TestMethod()]
public void SaveTimeTest()
{
double expected = (new Random()).Next(10000);
double actual;
CacheHelper.SaveTime = expected;
actual = CacheHelper.SaveTime;
Assert.IsTrue(expected==actual);
}
}
public class CacheHelperTest
{
/// <summary>
///Get 的测试
///</summary>
[TestMethod()]
public void GetTest()
{
string key = "key";
object actual = CacheHelper.Get(key);
Assert.IsNull(actual);
Cache cache = HostingEnvironment.Cache;
string value="value";
cache.Insert(key,value);
actual = CacheHelper.Get(key);
Assert.IsNotNull(actual);
Assert.IsTrue(actual.ToString()==value);
}
/// <summary>
///Get 的测试
///</summary>
[TestMethod()]
public void GetWithAbnormalParameterTest()
{
object actual = CacheHelper.Get(string.Empty);
Assert.IsNull(actual);
actual = CacheHelper.Get(null);
Assert.IsNull(actual);
}
/// <summary>
///GetKeys 的测试
///</summary>
[TestMethod()]
public void GetKeysTest()
{
int count = (new Random()).Next(10);
IList<string> keys = CreateAllKeys(count);
InsertAllKeys(keys);
IList<string> results = CacheHelper.GetKeys();
Assert.IsTrue(results.Count == count);
for (int index = 0; index < count; index++)
{
Assert.IsTrue(results.Contains(keys[index]));
}
for (int index = 0; index < count; index++)
{
Assert.IsTrue(keys.Contains(results[index]));
}
}
private void InsertAllKeys(IList<string> keys)
{
Cache cache = HostingEnvironment.Cache;
foreach (string key in keys)
{
cache.Insert(key,key);
}
}
private IList<string> CreateAllKeys(int count)
{
IList<string> keys = new List<string>();
for (int index = 0; index < count; index++)
{
keys.Add("KEY"+index.ToString());
}
return keys;
}
/// <summary>
///Remove 的测试
///</summary>
[TestMethod()]
public void RemoveTest()
{
int count = 1;
IList<string> keys = CreateAllKeys(count);
InsertAllKeys(keys);
string key = keys[0];
IList<string> results = CacheHelper.GetKeys();
Assert.IsTrue(results.Contains(key));
CacheHelper.Remove(key);
results = CacheHelper.GetKeys();
Assert.IsFalse(results.Contains(key));
}
/// <summary>
///RemoveAll 的测试
///</summary>
[TestMethod()]
public void RemoveAllTest()
{
int count = (new Random()).Next(20);
IList<string> keys = CreateAllKeys(count);
InsertAllKeys(keys);
IList<string> results = CacheHelper.GetKeys();
foreach (string key in keys)
{
Assert.IsTrue(results.Contains(key));
}
CacheHelper.RemoveAll();
results = CacheHelper.GetKeys();
Assert.IsTrue(results.Count==0);
}
/// <summary>
///SaveTime 的测试
///</summary>
[TestMethod()]
public void SaveTimeTest()
{
double expected = (new Random()).Next(10000);
double actual;
CacheHelper.SaveTime = expected;
actual = CacheHelper.SaveTime;
Assert.IsTrue(expected==actual);
}
}
这个上面的仅仅是对一些基本的方法进行了单元测试,基本验证了方法的逻辑,当然不包括那些重载方法的验证。至于为什么写这样相关的类,主要是能够以静态的方法来对Cache进行统一的操作,仅仅是为了方便与统一。
源代码下载:缓存类与单元测试源代码下载