How to manage cache in asp.net
When explaining the cache management mechanism, let me first clarify the next concept: Data Management under IE. Everyone will use different methods to solve how to manage data in IE. Some will mention the use of status management, some mention the cache Management, here I prefer cache Management, because I prefer the word "cache. However, status management and cache Management are different in terms of concept and meaning. Let's discuss the differences between the two in various aspects.
Although cache Management does not exist in Windows programs, it has been widely used in web environments. Since HTTP becomes protocol-free, it is very difficult to distinguish two different requests on the WEB. How to distinguish so many requests becomes very important. If it is the same request, we can cache the data for all users on the web to access and reduce data duplication for physical loading.
Asp.net provides several methods to cache data on the client and server, but we are often worried about which method to use. Asp.net provides the following three implementation methods:
1: Session; 2: Application 3: Cache objects. We must be very clear about their advantages so that we can make full use of their advantages in web programs.
Background:
In this article, I will briefly introduce different functions in cache Management. In web programs, we want to avoid performance problems caused by high concurrency data access, it is necessary for us to cache data on the server so that later accesses can directly call the cached data to play a role in data reuse.
Cache helps us to mention three important aspects of service quality:
Performance: the cached data is reused to avoid repeated physical data loading.
Measurable: After data is cached, data is loaded from the server.
Practicality: if other systems or databases crash, data can still be obtained from the cache without being affected by local hardware.
In a web program, we can cache data, cache pages, and so on. Let's take a look at the differences between the data cache on the server and the client.
1. Server cache:
1.1Session status management:
Session caches data for everyone. That is to say, the cached data cannot be shared by multiple people at the same time, but is limited to cache data for individual users.
There are three methods to implement status management:
1.11: InProc:
Local data is stored in the aspnet_wp.exe process, and data is lost due to IIS restart.
1.12: StateServer:
Different from InProc, it can be stored on different servers.
1.133: SQLServer:
Its data is stored in the database, and the data will not be lost due to IIS restart.
The biggest difference between the last two methods and InProc is that we need to ensure that the cached data is serializable, otherwise it can only be used in the first method. therefore, we need to carefully analyze and select the most suitable method.
The following is the code snippet of how the Session works:
Code
String empNum = Request. QueryString ["empnum"];
If (empNum! = Null)
{
String details = null;
If (Session ["EMP_DETAILS"] = null)
{
// Get Employee Details for employee number passed
String details = GetEmployeeDetails (Convert. ToInt32 (empNum ));
Session ["EMP_DETAILS"] = details;
}
Else
{
Details = Session ["EMP_DETAILS"];
}
// Send it to the browser
Response. Write (details );
}
1.2 ASP. NET application
Asp.net provides another method for saving global variables. The Application object is also oriented to all users, and its lifecycle is the same as that of applications, after the application is initialized, it starts to be rebuilt. But its biggest drawback is that there is no relevant data expiration method, and cache Management is required at this time.
1.3 ASP. NET cache
Cache is my favorite mechanism, which is why I like to talk about it. It provides a key-value method, and the namespace corresponding to the cache is: System. Web. Caching. its lifecycle also depends on the application process.
But it is not like session, which is also intended for all users. Although the cache looks especially like an application, the biggest difference is that it provides a data cache failure control method and data cache dependency management. That is to say, in the cache, we can easily set the expiration time for the cache to expire and delete the cache. We can also operate the cache based on the cache dependency, when the dependency relationship is changed, the cache automatically becomes invalid. This is not what applicaion can do.
Now let's take a look at how asp.net supports cache expiration and data cache dependencies.
1.31: cache dependency:
As the name implies, the cache will become invalid when the preset dependency changes. Asp.net provides two dependency relationships:
1.311: File cache dependency: the cache is automatically invalidated when a file on the disk changes.
The following is the instance code:
Object errorData;
// Load errorData from errors. xml
CacheDependency fileDependency =
New CacheDependency (Server. MapPath ("errors. xml "));
Cache. Insert ("ERROR_INFO", errorData, fileDependency );
1.312: Key-value cache dependency: It looks very similar to the File cache. In addition, this dependency method is different. When multiple cache information is associated with each other, changes in the information of a cache will cause the failure of other caches. For example, a user information includes: number, name, address, etc. If the user ID changes, the cache becomes invalid. In this case, the basic user information depends on the user ID.
The following is the sample code:
String [] relatedKeys = new string [1];
RelatedKeys [0] = "EMP_NUM ";
CacheDependency keyDependency = new CacheDependency (null, relatedKeys );
Cache ["EMP_NUM"] = 5435;
Cache. Insert ("EMP_NAME", "Shubhabrata", keyDependency );
Cache. Insert ("EMP_ADDR", "Bhubaneswar", keyDependency );
Cache. Insert ("EMP_SAL", "5555 USD", keyDependency );
1.32: Expiration Policy: it automatically expires after a period of time since the cache is created.
Sample Code:
// Absolute Expiration
Cache. Insert ("EMP_NAME", "Shubhabrata", null,
DateTime. Now. AddDays (1), Cache. NoSlidingExpiration );
// Sliding Expiration
Cache. Insert ("EMP_NAME", "Shubhabrata", null,
Cache. NoAbsoluteExpiration, TimeSpan. FromSeconds (60 ));
1.4 ASP. NET page output Cache
Sometimes some pages on the web site will not change for a long time. For example, for a recruitment website, the description of the salary is generally not changed, it is generally changed once a month, so the content you see is the same in this month. It is not a perfect solution to cache data on the server. The page output cache can be used here.
The following is the sample code:
<% @ OutputCache Duration = "60" VaryByParam = "empNum"
Location = "Server" %>
2: Client Cache:
In the above article, I discussed some data caching methods on the server. However, sometimes we need to cache some data to the client to improve performance. This mechanism can be used to relieve the pressure on the server. However, there may be various security issues in the client cache data. I will briefly describe the related content below:
2.1 Cookies: cookies are widely used in WEB application development. They can easily access each other on the client and server. However, they have a data size limit of up to 4 kb, it is often used to store small data. At the same time, cookies also support perfect control over invalidation.
The following is the sample code:
If (this. Request. Cookies ["MY_NAME"] = null)
{
This. Response. Cookies. Add (new HttpCookie ("MY_NAME ",
"Shubhabrata Mohanty "));
}
Else
{
This. Response. Write (this. Request. Cookies ["MY_NAME"]. Value );
}
2.2 ViewState: ViewState is a brand new concept. It is generally used for retaining data in pages or controls for transportation to the server. In ASP, we store data by using a Hidden control (Hidden fields). ViewState is also used, but it is more secure than a Hidden control, all values are processed by hash. If you view the page source code, you will see the existence of ViewState. Generally, ViewState does not need to be used to save big data.
The following is the sample code:
Protected void Page_Load (object sender, EventArgs e)
{
If (this. ViewState ["MY_NAME"] = null)
{
This. ViewState ["MY_NAME"] = "Shubhabrata Mohanty ";
}
// TxtName is a TextBox control
This.txt Name. Text = this. ViewState ["MY_NAME"]. ToString ();
}
2.3 hide the Hidden fields control: it is the simplest and needless to say
The following is the sample code:
<! -- In ASP. NET -->
<Asp: HiddenField ID = "myHiddenField" Value = "Shubhabrata"
Runat = "server"/>
<! -- In HTML -->
<Input id = "myHiddenField" type = "hidden" value = "Shubhabrata"/>