Web Service 缓存
由于微软的Web service实现是基于Asp.net,所以会出现缓存也就在情理之中了.主要有2中缓存:输出缓存和数据缓存.由于Web Service的缓存管理与asp.net基本是一样的,就不说他的原理,主要说一下在Web service中是如何实现的.
输出缓存
实现方法是在WebMethod这个特性里面加一个属性CacheDuration,如下代码所示
[WebMthod(CacheDuration=30)]
public string HelloWorld(){...}
其单位为秒.
数据缓存
数据缓存主要是存储在Context.Cache之中.而关于数据缓存有一个比较通用的设计模式.
那就是建立一个private 方法,拿取所有的数据(相对所有的数据,依据项目情况而定),并把数据缓存起来,在建议各public的WebMethod方法,此方法就从私有的方法过滤出相关的数据返回给客户端.代码片段如下
private DataSet GetAllUsers()
{
DataSet ds =new DataSet();
if(Context.Cache["cachename"] !=null)
{
return (DataSet)Context.Cache["cachename"];
}
else
{
//....some code to retrieve data from some store
//cache
Context.Cache.Insert("cachename",ds,null,DateTime.Now.AddMinutes(10),TimeSpan.Zero);
return ds;
}
}
//retrieve all users that belongs to a department.
[WebMethod]
public User[] GetUser(string DeptID)
{
DataSet alluser = GetAllUsers();
User[] users =alluser.Tables[0].Rows[5] //注:此处代码仅仅是示例,本身语法是有问题,主要是说明在alluser对象中依据传过来的部门参数进行过滤后,然后返回.
}