WebService的缓存机制

C#, WebService, 技术心得 Add comments

  WebService的缓存分为两种,一种是简单的输出缓存,一种是强大的数据缓存

  一、输出缓存
  输出缓存的使用非常简单,比较适用于WebService的参数比较少,结果比较单一的情况,例如股票信息,可以设置5-10秒的缓存,天气预报,则可以设置30分钟甚至数小时的缓存。使用方法是,在WebMethod属性上指定CacheDuration属性即可,例如

[WebMethod(Description = "Test",CacheDuration=600)]
public string Test()
{
      return "Test";
}

  这样,600秒内这个WebService的所有输出数据都将从缓存中读取,不会真正做数据处理,如果事务代码是访问数据库的话,现在这种方法就会比每次都访问数据库快得多。这种缓存适合初接触WebService的新手使用。
  要注意的是,不是所有服务都适合使用这种缓存,例如每次结果都不一样的,访问数极高的服务,缓存将会变得非常大,占用很多服务器的内存,却没有实际效果。

  二、数据缓存
  想将你的WebService某些运行数据保存起来?如果不使用本地的数据库或者文件,那么缓存是最好的选择。这种缓存不同于上面提到的输出缓存,它需要编写代码来实现,但是相对应的,它的功能非常强大,可以存放任何类型的信息,并且你可以在任何时候检索它。
  虽然也可以使用Application来模拟缓存,但是这需要你自己管理内存释放、用户并发问题,在.net时代已经被抛弃,WebService下的缓存使用Cache这个集合

using System.Web.Caching;
[WebMethod(Description = "Test")]
public string Test()
{
        string Content = "just4test";
 
        //创建数据缓存
        Context.Cache.Insert("Test", Content, null, DateTime.MaxValue,TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
 
        string result = Context.Cache["Test"].ToString();
        return result;
        }
}

  在这里,我们使用了Context.Cache属性,Context.Cache.Insert方法用于将数据加入缓存。这个方法一共有4种重载,在这个例子中,我们使用的是功能最全面的重载版本,我们以此为例:每一个参数分别是键名(使用方法类似于Session),值,依赖性,绝对过期时间,可变过期时间,缓存优先级,缓存项目删除时的委托方法绝对过期时间是固定的,DataTime.MaxValue在这里表示永不过期;可变过期时间是一定时间内该缓存没有使用则自动失效,此处TimeSpan.Zero表示不使用可变过期。注意两者只能设置一项,如果要使用可变过期,绝对过期必须是DataTime.MaxValue,例如

Context.Cache.Insert("Test", Content, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));

  缓存优先级是Web服务器清理它的可能性,在此的CacheItemPriority.NotRemovable表示通常不从缓存中删除,可以理解为永久性缓存
  通过依赖性,可以监视某个文件或者其他缓存的改动,如果有变化,则此缓存失效,这非常有实用价值。例如:

CacheDependency de = new CacheDependency(Server.MapPath("1.xml"));
Context.Cache.Insert("Test", Content, de, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);

  这样,1.xml文件被删除或者更改的时候,缓存就会失效

  三、实用举例
  实际使用中,我使用这样一段代码,当远程的某个文件更新时,必须下载到本地,而缓存负责保存该文件的文件名和修改时间,每次客户端请求文件名和时间的时候,直接从缓存读取。每次定时下载程序(另有代码)启动的时候,getFiles()方法先检查是否有新文件(与本地缓存比对),然后决定是否下载。

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
using TestOp;
using System.Web.Caching;
[WebService(Namespace = "Test")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Test: System.Web.Services.WebService
{
 //提供下载和分析功能的后台代码类,TestOP
 private TestOp testOp;
 
 public Test()
 {
 testOp = newTestOp();
 }
 
 [WebMethod(Description = "下载文件")]
 public string getFiles()
 {
  if (Context.Cache["FileName"] != null)
  {
   string FN=Context.Cache["FileName"].ToString();
   testOp.GetHTML();
   testOp.GetMatch();
   if (FN.CompareTo(testOp.CheckFileName()) != 0)
   {
    try
    {
     testOp.Download();
     Context.Cache.Insert("Time", testOp.CheckTime(), null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
     Context.Cache.Insert("FileName", testOp.CheckFileName(), null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
 
 return "ok";
 }
 catch
 {
  return "Ex";
 }
 }
 else
 {
  return "ok";
 }
 }
 else
 {
  try
  {
   testOp.GetHTML();
   testOp.GetMatch();
   testOp.Download();
   Context.Cache.Insert("Time", testOp.CheckTime(), null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
   Context.Cache.Insert("FileName", testOp.CheckFileName(), null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
 
 return "ok";
 }
 catch
 {
  return "Ex";
 }
 }
 
 }
 
 [WebMethod(Description = "检查最新文件时间")]
 public string CheckTime()
 {
  if (Context.Cache["Time"] ==null)
  {
   try
   {
    this.getFiles();
    string result = Context.Cache["Time"].ToString();
 
    DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
    return result;
   }
   catch
   {
    return "Ex";
   }
  }
  else
  {
   string result = Context.Cache["Time"].ToString();
   return result;
  }
 
 }
 
 [WebMethod(Description = "检查最新文件名")]
 public string CheckFileName()
 {
  if (Context.Cache["FileName"] == null)
  {
   try
   {
    this.getFiles();
 
    string result = Context.Cache["FileName"].ToString();
    return result;
   }
   catch
   {
    return "Ex";
   }
  }
  else
  {
   string result = Context.Cache["FileName"].ToString();
   return result;
  }
 }
 
}

Related posts:

  1. Directory Opus 联网验证被封证书后,清除安装痕迹的方法

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


LilyStudio & WordPress & N.Design Studio
Entries RSS Comments RSS Log in