net How to use the Cache framework to add Cache to a program

  • 2021-10-13 07:00:47
  • OfStack

In NET 4.0, a namespace of System. Runtime. Caching is added, which provides a series of extensible Cache framework. This paper briefly introduces how to use it to add Cache to the program under 1.

An Cache framework mainly includes three parts: ObjectCache, CacheItemPolicy and ChangeMonitor.

ObjectCache represents an CachePool, which provides interfaces such as adding, obtaining and updating Cache objects, and is the main body of Cache framework. It is an abstract class, and the system gives a commonly used implementation-MemoryCache.
CacheItemPolicy means Cache expiration policy, for example, expire after saving for 1 fixed time. It is also often used with ChangeMonitor1 to implement more complex strategies.
ChangeMonitor is mainly responsible for maintaining the state of CachePool objects and judging whether the objects need to be updated. It is also an abstract class, and the system also provides several common implementations: CacheEntryChangeMonitor, FileChangeMonitor, HostFileChangeMonitor, SqlChangeMonitor.

1. First, create a new 1-class control program and add a class, in which the code is as follows


#region 
class MyCachePool
  {
    ObjectCache cache = MemoryCache.Default;
    const string CacheKey = "TestCacheKey";

    // Defining String Type Constants CacheKey And assign the initial value to TestCacheKey , then it can't be changed again CacheKey Value of  
    // Such as execution CacheKey="2";  Errors will run throughout the program  a The value of is always TestCacheKey


    public string GetValue()
    {
      var content = cache[CacheKey] as string;
      if(content == null)
      {
        Console.WriteLine("Get New Item");


           //SlidingExpiration = TimeSpan.FromSeconds(3)
        // No. 1 1 This kind of expiration policy, when the object 3 If it is not accessed within seconds, it will expire. If the object 1 If it is accessed directly, it will not expire. 

        AbsoluteExpiration = DateTime.Now.AddSeconds(3)
        // No. 1 2 A kind of expiration strategy, when exceeding 3 Seconds later, Cache The content will expire. 


        content = Guid.NewGuid().ToString();
        cache.Set(CacheKey, content, policy);
      }
      else
      {
        Console.WriteLine("Get cached item");
      }

      return content;
    }

#endregion

Then in the main program entrance


   static void Main(string[] args)
   {
        MyCachePool pool = new MyCachePool();
        MyCachePool1 pool1 = new MyCachePool1();
        while(true)
        {
                  Thread.Sleep(1000);
                  var value = pool.GetValue();
                  //var value = pool1.myGetValue();
                  Console.WriteLine(value);
                  Console.WriteLine();
   }

}

This example creates an Cache that is saved for 3 seconds: the same value is obtained within 3 seconds. After more than 3 seconds, the data expires, and Cache is updated to obtain a new value.

Expiration policy:

From the previous example, we can see that when an Cache object is added to CachePool, an CacheItemPolicy object is added at the same time, which realizes the overdue control of Cache object. For example, in the previous example, we set the timeout policy as follows: AbsoluteExpiration = DateTime. Now. AddSeconds (3). It means that 1 absolute time has expired, and when it exceeds 3 seconds, Cache content will expire.

In addition, we also have a common overdue strategy: to determine the overdue according to the frequency of visits. For example, if we set the following overdue policy: SlidingExpiration = TimeSpan. FromSeconds (3). It means that when the object is not accessed within 3 seconds, it will expire. In contrast, if Object 1 is accessed directly, it will not expire. These two strategies cannot be used at the same time. So I have commented in the above code.

CacheItemPolicy can also formulate UpdateCallback and RemovedCallback, which is convenient for us to record logs or perform some processing operations, which is very convenient.

ChangeMonitor

Although the expiration strategy listed above is a very common strategy, it can meet our needs most of the time. But sometimes, the expiration strategy can't be judged simply by time. For example, the content of my Cache is read from a text file. At this time, the expiration condition is whether the file content has changed: when the file has not changed, the content of Cache is directly returned. When asked about the change, the content of Cache is overdue and needs to be re-read. At this time, ChangeMonitor is needed to realize more advanced overdue judgment.

Since the system has provided file changes ChangeMonitor-HostFileChangeMonitor, here do not need to achieve their own, can be used directly.


  public string GetValue()
  {
    var content = cache[CacheKey] as string;
    if(content == null)
    {

     Console.WriteLine(" No. 1 2 Kinds of expiration methods ");
     var file = "C:\\Users\\Administrator\\Desktop\\test.txt";
     CacheItemPolicy policy = new CacheItemPolicy();
     policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { file }));
     content = File.ReadAllText(file, Encoding.Default); //Encoding.Default Used to solve the garbled problem 

     //StreamReader sr = new StreamReader(file, Encoding.Default);
     //content = sr.ReadToEnd();
     //sr.Close();
    // No. 1 2 Kinds of reading modes 

    cache.Set(cacheKey, content, policy);


    }
    else
    {
      Console.WriteLine("Get cached item");
    }

    return content;
  }

This example is still relatively simple, for those who do not have a custom policy, we need to implement our own ChangeMonitor. Next time, I will write an article to introduce it in depth.


Related articles: