asp.net SAF 中缓存服务的实现第4/5页
更新时间:2008年08月08日 21:28:49 作者:
对缓存的兴趣源于张子阳写的一篇文章《SAF 中缓存服务的实现》中的一个例子:
最后的两个方法,GetItem()和GetList()分别用于从缓存中获取单个或者多个对象。值得注意的是当使用GetList()方法时,Xpath应该为到达一个组结点的路径。
复制代码 代码如下:
// 根据 XPath 获取对象
// 先根据Xpath获得对象的Key,然后再根据Key获取实际对象
public virtual object GetItem(string xpath) {
object obj = null;
xpath = PrepareXPath(xpath);
XmlNode node = rootMap.SelectSingleNode(xpath);
if (node != null) {
// 获取对象的Key
string key = node.Attributes["key"].Value;
// 获取实际对象
obj = cacheStrategy.GetItem(key);
}
return obj;
}
// 获取一组对象,此时xpath为一个组结点
public virtual object[] GetList(string xpath) {
xpath = PrepareXPath(xpath);
XmlNode group = rootMap.SelectSingleNode(xpath);
// 获取该结点下的所有子结点(使用[@key]确保子结点一定包含key属性)
XmlNodeList results = group.SelectNodes(xpath + "/*[@key]");
ArrayList objects = new ArrayList();
string key;
foreach (XmlNode result in results) {
key = result.Attributes["key"].Value;
Object obj = cacheStrategy.GetItem(key);
objects.Add(obj);
}
return (object[])objects.ToArray(typeof(object));
}
至此,SAF 的缓存服务的设计和代码实现都完成了,现在我们来看看如何使用它。
程序测试
复制代码 代码如下:
static void Main(string[] args) {
CacheService.Cache cache = CacheService.Cache.Instance;
// 添加对象到缓存中
cache.AddItem("/WebApplication/Users/Xin", "customer xin");
cache.AddItem("/WebApplication/Users/Jimmy", "customer jimmy");
cache.AddItem("/WebApplication/Users/Steve", "customer other");
cache.AddItem("/WebApplication/GlobalData", "1/1/2008");
cache.AddItem("/Version", "v10120080401");
cache.AddItem("/Site", "TraceFact.Net");
// 获取所有User
object[] objects = cache.GetList("/WebApplication/Users");
foreach (object obj in objects) {
Console.WriteLine("Customer in cache: {0}", obj.ToString());
}
// 删除所有WebApplication下所有子孙结点
cache.RemoveItem("/WebApplication");
// 获取单个对象
string time = (string)cache.GetItem("/WebApplication/GlobalData");
string name = (string)cache.GetItem("/WebApplication/Users/Xin");
Console.WriteLine("Time: {0}", time);// 输出为空,WebApplication下所有结点已删除
Console.WriteLine("User: {0}", name);// 输出为空, WebApplication下所有结点已删除
// 获取根目录下所有叶结点
objects = cache.GetList("/");
foreach (object obj in objects) {
Console.WriteLine("Object: {0}", obj.ToString());
}
Console.ReadLine();
}
输出的结果为:
Customer in cache: customer xin
Customer in cache: customer jimmy
Customer in cache: customer other
Time:
User:
Object: v10120080401
Object: Trace


最新评论