Elaborate .NET Cache

In project development it can be said to have been a cache of existence, but specifically how to use caching technology used where, for most developers do not know, and even some developers believe that the cache is too complicated to use. So through this article you readers can fully understand the use of the cache and principles.

First, what is the cache

  1. Cache can do

Cache can improve system performance, improve stability and usability. The same cache can also reduce the amount of traffic interaction, reduce system throughput and reduce disk overhead. Now I am a simple overview of the six previously mentioned for the content.

  • Improve system performance: the cached data to avoid duplication of data processing and transmission, usually we will change in the cache, such as national, provincial and city names little data storage;
  • Improve stability: multiple calls at the large number of requests for the same data or logic will cause a great waste of resources, or even result in system instability. Then we can use these cached resources are read from the cache every request, thus improving the stability of the system;
  • Improve usability: when the data system service problems, you can continue to provide data services to the requester through the cache, but this time the data may be outdated;
  • Reducing traffic: cache data can effectively reduce the amount of transmission between processes and machines;
  • Reducing the amount of processing: the processed data cached to avoid reprocessing the same data;
  • Reduce the number of disk access: the data cached, each time when the need to access the data cache, if there is cached data is returned, if not present then the data stored on disk access. Can effectively reduce the amount of disk access by this operation.
  1. Buffer state

The so-called buffer state is a point in time in the application system state data, these data may be persisted to the database, and so there may be temporarily stored in memory. In this section we will learn in the cache lifecycle, and how the scope of stale data processing.

  • Cache life cycle

Cache life cycle a total of four, respectively, in the following table:

Life cycle Explanation
Permanent State Permanent: data never expires, there is a permanent data
Process State Effective process: process data in the effective life cycle effective
Session State The session is valid: valid within a particular session data
Message State The message is valid: effective period of treatment of a particular message
  • Cache scope

There is a range of cache, cache To sum up the range include two categories: physical and logical scope range. Within the scope of these two also contains a range of different levels of detail. details as follows:

  • Physical range
range Explanation
Organization Within the organization that all applications can access the cache
Farm In the field of application range of all machines can access the cache
Machine In a single machine can access the cache
Process Within an application process can access the cache
AppDomain In one application domain can access the cache
  • Logic range
range Explanation
Application Within an application process can access the cache (with the Process)
Business Process You can access the cache within specific business processes
Role Specific role can access the cache
User A particular user can access the cache
  • Cache stale data processing

Cache is a snapshot of the data, but due to a data source can be modified, so there is stale cache features. Old negative impact on data use of this feature will be an important task to minimize buffer status data. Generally, we define the following two aspects from which the data is stale data:

  • The possibility of master data changes: the possibility of longer master data is modified, the greater, so we can set up some time to update the cache data;
  • The degree of influence of old data: data cache is not updated or not updating any impact on the entire system or core business.

According to the above two criteria, we will define the acceptable level of tolerance for the cached data, into intolerable tolerance and a certain degree of tolerance. The so-called intolerable, that is, when the main data update cached data must be updated immediately. And refers to a degree of tolerance is allowed over a certain period and the primary data cache data differ.

  1. Something that should be considered

When using the cache, we should consider five aspects:

  • Expiration policy: Define how long the cached data failure, failure in what circumstances;
  • Security: how to ensure that the cached data is not accessed by others without permission process, method;
  • Management: The maximum capacity is defined cache, and clean-up expiration policy strategies;
  • Data formats and access methods: selection thread safe, and the sequence can be normalized, and a method of caching programs;
  • Content Load: How the content is loaded, it is loaded in advance when the application is started, or to start using the acquired data to the main data, after then placed in the cache.

Two, .NET Caching

.NET Caching There are seven, namely: Asp.net cache, Remoting Singleton Cache, Memory-Mapped File, SQL Server cache, cache static variables, Asp.net session state and client cache. Now I were to explain in detail.

  1. Asp.net cache

For Asp.Net developers often need to store frequently used data in memory. The method is nothing more than three, including the most commonly used is the Session object and the Application object . Both are ways to cache data in the form of key-value pairs. The only difference is that Talia Session object is stored and data related to a single user, while Application object is stored and data related to the application, each user can access. In addition to these two methods, there is another method is not very common, but convenient than the above method. This method is the Cache object , which is dedicated to the Asp.Net cache data, its application range is the entire application domain. Life cycle and application, as when the application starts Cache object is created when the application is closed Cache object disappeared. It has features specifically for cache management, here we look at Cache explanation (Session object and the Application object because more use is therefore not explained here).
Cache object in the namespace System.WebCaching , which in addition to the external storage key, you can also store the object .NET framework. Under normal circumstances we use Cache Cache property of the Page object or property HttpContext class to get a reference to the Cache. When we first need to consider using Cache is dependent and expiration policies. Asp.Net dependence and the expiration policy contains the following two:

  • File Dependency: file dependency, when one or more files on the hard disk changes, mandatory removal of cached data.
  • Time-based expiration policies: the failure of the data in accordance with pre-defined time policy, parameter can be an absolute time or a relative time.

Tip:

  1. Cache object according to the priority cache entry to determine which cache data to be removed, you can specify the priority of cache entries in the code. Use designated priority value CacheItemPriority enumeration item.
  2. Asp.Net does not provide a cache refresh, but we can use Response.Cache.SetExpires method to set the expiration date to the current date data, you can refresh the cache.

In Asp.Net, we can also be output buffer, the output buffer is mainly used to cache pages. The response page request into the cache, subsequent requests will get on this page from the cache. We can be accomplished by adding the Page directive, it can also be achieved by HTTPCachePolicy class. Cached pages when we need to consider the following aspects:

  • But does not change frequently requested static pages;
  • Update frequency and time known page (such as stock price display page);
  • According to the HTTP parameters, there may be several pages of output (such as city code display page according to the city's weather conditions);
  • From the results returned by the Web Service.

Sometimes store the entire page will lead to excessive memory usage, this time should use the page fragment caching. But the page fragment caching technology is not applicable at all times, only the following situations apply:

  • Multiple pages clips used by the user;
  • Page fragment that contains static data;
  • Spending a lot of page fragments;
  • Multiple pages using page fragments together.
  1. Remoting Singleton Cache

.Net provides cross-application domain, cross-process and cross-frame computer program is run. Singleton activation server object type at any time not simultaneously have multiple instances. In the present instance, if during operation, all client requests service provided by this example. If not, the server will create an instance, all subsequent requests by that instance to provide services.

  1. Memory-Mapped File

Memory-Mapped File allows applications to access files on the disk through a pointer. This method of shared memory when a plurality of applications, the system performance will be significantly improved. Memory-Mapped File-based caching scheme can be used in each layer of the application, but due to the use win32 API calls, so the only way to run unmanaged code.

  1. SQL Server Cache

The cached data stored in the database is also commonly used methods, its advantages are as follows:

  • Easy to implement;
  • Comprehensive security model and high robustness;
  • Easily share;
  • Persisted;
  • Support large amount of data.

Of course, the drawback is obvious:

  • You need to install SQL Server, it is not appropriate for small applications;
  • Performance Performance reconstructed data read from the database and comparison;
  • Large burden on the network.
  1. Static variable cache

The data store is declared as static variables, and provide a maintenance interface, because it is in memory, this scheme may provide direct, high-speed access to the cached data, if no alternative solutions to store the key value and speed demanding , you can use static variables. Object premise using this method of preservation is that it does not change often, but because there is no mechanism to clear the cache, so this method can cause significant performance overhead, and also to ensure thread safety. Therefore, this method is not recommended.

  1. Asp.net session state

Based on asp.net session state HttpSessionState objects to cache an individual user's session state information, solve a lot of restrictions in session state asp. Asp.net session state has three modes of operation:

  • In-process mode InProc:

In-process mode is the only mode supported Session_End event session, when the user session times out or abort, you can run Session_End in the event-handling code to clean up resources. But aspnet_wp.exe multiple instances of the web application running on the same server, so the in-process mode NA web application.

  • Of-process mode State Server:

This mode uses the specified process to store state information, use this mode to ensure that you store objects that can be serialized. When used in web applications it is necessary to ensure the web.config file elements are unique on all servers. So that all servers use the same
kind of encryption to access the data in the cache.

  • SQL server mode:

This mode is similar to SQL Server cache, not much to explain here.

  1. Client-side caching

Use client-side storage page information of ways to reduce the burden on the server, while having the lowest security and the most limited amount of data, but they have the fastest performance. Client-side caching commonly used method has the following five categories:

  • Hidden Field

This method is the so-called hidden field, placed in a page <input type="hidden"/>, deposit required buffer value in its value property. The advantage of this is submitted together with the form, but all browsers and server support and nothing to do. But also has the disadvantage, insecurity, anyone can modify and store structured data is not convenient, there will be a lot of content performance problems.

  • View State

Hidden Field This method and the same method, but this method of data storage is encrypted, but also has the disadvantage of Hidden Field.

  • Hidden Frame

Use Hidden Frame, avoiding every page cache data loopback and from the use of hidden field and use view state, advantage is that you can load large amounts of data, you can cache multiple different data. Drawback is also very difficult, first of many browsers have begun Frame does not support it, and the client can see the hidden Frame, and a large number of Frame will cause slow page loads.

  • Cookies

Cookies can also store cached data can be easily stored in the client browser, and supports expiration policy, but the disadvantages are also obvious. First vulnerable to tampering, and may be stored in a limited number of Cookie and the client is likely to reject Cookie.

  • Query String

This method can be used only when using HTTP GET invoke the URL, the server can be read directly, but all browsers can use, but because it is displayed in the URL, it is vulnerable to tampering, and have length restrictions, character can not be more than 255 characters.

Third, the summary

Through the above explanation, I believe we have to understand the use of the cache, scenes and methods of use of our attention should use to use.
The method can be used only when using HTTP GET invoke the URL, the server can be read directly, but all browsers can use, but because it is displayed in the URL, it is vulnerable to tampering, and have length restrictions, characters can not more than 255 characters.

Third, the summary

Through the above explanation, I believe we have to understand the use of the cache, scenes and methods of use of our attention should use to use.

Published 204 original articles · won praise 101 · Views 350,000 +

Guess you like

Origin blog.csdn.net/gangzhucoll/article/details/104035088