[Crawler learning notes] MemoryCache usage learning, memorycache

Source: Internet
Author: User

[Crawler learning notes] MemoryCache usage learning, memorycache

   

After completing the DNS resolution module, I realized that the DNS cache mechanism is also necessary. In Redis, Memcache, and. net built-in Cache, considering the deployment problem, finally chose the latter, before learning the Web and development process using System. web. caching. cache class library, but this crawler I plan to deploy as desktop software, so I chose System. runtime. caching. memoryCache (System will be added later if necessary. web. caching. cache to adapt to Web applications ).

The usage of MemoryCache is not described on the Internet, but this is. the new cache object introduced by NET4.0 is estimated to replace the cache module of the original enterprise library, so that.. NET caches can be everywhere, instead of being used based on a specific version of Windows.

For convenience, we will not create a new MemoryCache object. We will only add, delete, and query the Default example Memory. Default of MemoryCache.

   

Basics

Added:

Var item = new CacheItem ("Xi Da", ""); var policy = new CacheItemPolicy (); policy. slidingExpiration = new TimeSpan (500); // insert a key to "Xi Da", and the value to "". The cached MemoryCache is automatically destroyed 500 milliseconds later. default. add (item, policy); // reset the expiration time of the policy to the current time + 10 minutes policy. absoluteExpiration = DateTimeOffset. now + TimeSpan. fromMinutes (10); // note that to use the Sliding time, Absolute must be DateTimeOffset. maxValue. Otherwise, the Sliding must be TimeSpan. zeropolicy. slidingExpiration = TimeSpan. zero; // re-insert to overwrite the previous data in MemoryCache. default. add (item, policy );

Note: If you want to use the Sliding time, then AbsoluteMust be DateTimeOffset. MaxValueOtherwise, SlidingMust be TimeSpan. Zero 
  

Query:

  

The cache object is similar to a dictionary set. You can use memoryCache [key] For queries. For example, you can query the data inserted earlier:

Var idea = MemoryCache. Default ["Xi Da"];
  

Remove:

Parameters

Key: the unique identifier of the cache item to be removed.
RegionName: A namearea in the cache with the cache items added. Do not pass a value for this parameter. By default, this parameter is NullBecause the MemoryCache class does not implement the region.
Return Value Type: System. Object if this item is found in the cache, It is the removed cache item; otherwise, it is null.

Delete the previously added item:

MemoryCache. Default. Remove ("Xi Da ");
  

Advanced

After understanding the basic usage, we can further encapsulate it to make it easier to use:

Using System; using System. collections. generic; using System. linq; using System. runtime. caching; namespace Crawler. common {/// <summary> /// cache helper class based on MemoryCache /// </summary> public static class MemoryCacheHelper {private static readonly object _ locker = new object (); public static bool Contains (string key) {return MemoryCache. default. contains (key) ;}/// <summary> /// obtain the Catch element /// </summary> /// <Typeparam name = "T"> type of the obtained element </typeparam> // <param name = "key"> key of the element </param> /// <returns> specific element value </returns> public static T Get <T> (string key) {if (string. isNullOrWhiteSpace (key) throw new ArgumentException ("invalid key! "); If (! MemoryCache. Default. Contains (key) throw new ArgumentException ("failed to get. This key does not exist! "); If (! (MemoryCache. Default [key] is T) throw new ArgumentException ("the required data type is not found! "); Return (T) MemoryCache. default [key];} /// <summary> /// Add the Catch element /// </summary> /// <param name = "key"> key of the element </param> /// <param name = "value"> element value </param> // <param name = "slidingExpiration"> element expiration time (interval) </param> /// <param name = "absoluteExpiration"> element expiration time (absolute time) </param> /// <returns> </returns> public static bool Add (string key, object value, TimeSpan? SlidingExpiration = null, DateTime? AbsoluteExpiration = null) {var item = new CacheItem (key, value); var policy = CreatePolicy (slidingExpiration, absoluteExpiration); lock (_ locker) return MemoryCache. default. add (item, policy );} /// <summary> /// remove the Cache element /// </summary> /// <typeparam name = "T"> type of the element to be removed </typeparam>/ // <param name = "key"> key of the element to be removed </param> // <returns> removed element </returns> public static T Remove <T> (string key) {if (str Ing. IsNullOrWhiteSpace (key) throw new ArgumentException ("invalid key! "); If (! MemoryCache. Default. Contains (key) throw new ArgumentException ("failed to get. This key does not exist! "); Var value = MemoryCache. Default. Get (key); if (! (Value is T) throw new ArgumentException ("the required data type is not found! "); Return (T) MemoryCache. default. remove (key) ;}/// <summary> /// Remove multiple cached data records, the default value is all caches. // </summary> /// <typeparam name = "T"> the cache type to be removed </typeparam> /// <param name = "keyList "> </param> // <returns> </returns> public static List <T> RemoveAll <T> (IEnumerable <string> keyList = null) {if (keyList! = Null) return (from key in keyList where MemoryCache. default. contains (key) where MemoryCache. default. get (key) is T select (T) MemoryCache. default. remove (key )). toList (); while (MemoryCache. default. getCount ()> 0) MemoryCache. default. remove (MemoryCache. default. elementAt (0 ). key); return new List <T> ();} /// <summary> /// set the expiration information /// </summary> /// <param name = "slidingExpiration"> </param> /// <param nam E = "absoluteExpiration"> </param> // <returns> </returns> private static CacheItemPolicy CreatePolicy (TimeSpan? SlidingExpiration, DateTime? AbsoluteExpiration) {var policy = new CacheItemPolicy (); if (absoluteExpiration. hasValue) {policy. absoluteExpiration = absoluteExpiration. value;} else if (slidingExpiration. hasValue) {policy. slidingExpiration = slidingExpiration. value;} policy. priority = CacheItemPriority. default; return policy ;}}}

Related Article

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.