The caching mechanism of C # WebService

Source: Internet
Author: User
Tags server memory

Go Caching mechanism of WebService February 19, 2008 Tuesday 11:22

WebService cache is divided into two types, one is a simple output cache, one is a powerful data cache

First, output cache
The use of the output cache is very simple, compared to the WebService parameters less, the result is relatively single case, such as stock information, can be set 5-10 seconds of cache, weather forecast, you can set 30 minutes or even hours of cache

Use this method:
You can specify the CacheDuration property on the WebMethod property, for example



This way, all of the output data for this webservice will be read from the cache in 600 seconds, not really data processing, and if the transaction code is accessing the database, it will now be much faster than accessing the database every time. This cache is suitable for beginners who have first contact with WebService.

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

Note that not all services are suitable for this kind of cache, for example, each time the results are different, access to a very high number of services, the cache will become very large, consuming a lot of server memory, but no actual effect.

Second, data cache
Want to save some of your webservice running data? If you do not use a local database or a file, caching is the best option. This kind of cache is different from the output cache mentioned above, it needs to write code to implement, but the corresponding, it is very powerful, can hold any type of information, and you can retrieve it at any time.

Although you can also use application to simulate caching, this requires you to manage memory release, user concurrency issues, and in the. NET era has been discarded, WebService cache using this collection

 

using System.Web.Caching;
[WebMethod (Description = "Test")]
public string Test ()
{
String Content = "Just4test";

Create a data cache
Context.Cache.Insert ("Test", Content, NULL, Datetime.maxvalue,timespan.zero, cacheitempriority.notremovable, NULL);

string result = context.cache["Test"]. ToString ();
return result;
}
}

Here we use the Context.cache property, which is used by the Context.Cache.Insert method to add data to the cache. There are 4 overloads in this method, in this case we are using the most comprehensive overloaded version, for example: Each parameter is a key name (using the same method as session), value, dependency, absolute expiration time, variable expiration time, cache priority, The delegate method when the cache item is deleted the absolute expiration time is fixed, Datatime.maxvalue here means never expires, and the variable expiration time is automatically invalidated if the cache is not used for a certain amount of time, where TimeSpan.Zero indicates that the variable expiration is not used. Note that you can only set one item, and if you want to use variable expiration, absolute expiration must be datatime.maxvalue, for example

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

The cache priority is the possibility that the Web server cleans it up, where the cacheitempriority.notremovable representation is usually not removed from the cache and can be understood as a persistent cache

With dependencies, you can monitor changes to a file or other cache and, if there is a change, this cache is useless, which is very useful. For example:

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

This will invalidate the cache when the 1.xml file is deleted or changed.

Third, practical examples
In actual use, I use this piece of code, when a remote file updates, must be downloaded to local, and the cache is responsible for saving the file name and modification time, each time the client requests the file name and time, read directly from the cache. The GetFiles () method checks for new files (as compared to the local cache), and then decides whether to download them each time the program (and another code) is started.

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 = "Download File")]
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 = "Check for latest file time")]
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 = "Check for latest filename")]
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;
}
}

}

The caching mechanism of C # WebService

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.