. Net Cache

Source: Internet
Author: User

 

There are three types of Asp.net cache: Page cache, data source cache, and data cache.

1,Page Cache

Principle: Page cache is the most common cache method. The principle is that when a user accesses the server for the first time, the Asp.net server saves dynamically generated pages to the memory, after a period of time, when another user accesses the page, the data in the memory is directly sent to him, instead of re-reading the database and dynamically generating the page. This reduces the burden on the database, this accelerates Website access.

Implementation Method:

Add the following code to the page header:

<%@ OutputCache Duration="20" VaryByParam="none" %>

 

Duration indicates the cache duration in seconds.

Varybyparam indicates the cache condition, and none indicates that only the page is cached. However, in this case, news. aspx? Id = 1 and news. aspx? Id = 2 reads news that are not used for two days, but only recognizes one page in the cache using the above method, and returns the same results for the night returned by passing different parameters, the solution is to specify the cache condition as ID, that is, varybyparam = "ID". If there are multiple parameters, you can use semicolons to separate varybyparam = "ID; num". If you do not want to specify the parameter, you can use varybyparam = "*". The Server caches all pages with no parameters.

 

2,Data Source Cache

Principle: The Server caches the data source when the user first accesses and reads the database. The next time the user accesses the database, the server directly caches the data, instead of reading the database again, different from page cache, the server only caches data sources, rather than the entire page.

Implementation Method:Specify the enablecaching = "true" attribute for the data source (objectdatesource, sqldatesource, accessdatesource, etc.)

<asp:AccessDataSource ID="AccessDataSource1" runat="server"             DataFile="~/App_Data/77feel.mdb" SelectCommand="SELECT * FROM [friend]"             EnableCaching="True" CacheDuration="30">        </asp:AccessDataSource>

 

Enablecaching = "true" indicates that cache is enabled.

Cacheduration = "30" indicates that the cache is 30 seconds.

 

3,Data Cache

Principle:Directly store the data in the server cache, which means that the data is stored in the memory.

Implementation Method:

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. ui; using system. web. UI. webcontrols; using system. data; public partial class cache: system. web. UI. page {protected void page_load (Object sender, eventargs e) {If (Cache ["friend"] = NULL) // determine whether the cache exists {jiang_db newdb = new jiang_db (); newdb. open (); dataset DS = newdb. re_dataset ("select * from [Friend]"); newdb. close (); cache ["friend"] = Ds. tables [0]. defaultview; // Save the data to the cache} repeater1.datasource = cache ["friend"]; // obtain the data from the cache repeater1.databind ();}}

 

The cache. Remove ("") method can remove the cache.

Use cache in ASP. NET
Cache is a high-speed cache. I think many people will have the same first impression on him as I do. I feel that it will certainly improve the system performance and speed. Indeed. The original intention of net to launch the cache is indeed this. So how does cache improve system performance and speed? Can I use cache to improve performance in any situation? Is it because the more cache is used, the better? I have some experience in recently developed projects. I hope to discuss it with you as a summary. If there are any mistakes, I hope you can criticize and correct them.

1. How the cache works.

L cache is a public memory disk allocated to the server.

The so-called public cache allows any client browser to access it through the background code when it is created. It targets all users, and session is also a piece of memory on the server, however, it targets a single user. It is a memory block of the server, that is, each cache occupies server resources once it is created. So from this point, we can say: the more cache, the better.

L The cache has a time limit. If the expiration time of the server is exceeded, the cache will be recycled by the server.

L c. cache can store any object

2. How to create and destroy the cache.

L create Cache

In. In the. NET environment, use the cache. insert (string key, object O) method. The key represents the cache ID, and O represents the object stored in the cache.

L destroy cache.

In the cache. Remove (string key) method, the key represents the cache ID.

L call cache.

Cache supports packing/unpacking. For example, you can cache a DataSet object DS through. insert ("dscache", DS) is stored in the cache. You can use dataset DS = (Dataset) cache ["dscache"] to access it.

 

 

3. When to use cache.

Cache is generally used when data is relatively fixed and frequently used. For example, you can store product information in the invoicing system into the cache, and call the cache when the user calls the product information, which greatly reduces the interaction between the user and the database, improves system performance. On the contrary, the cache is not suitable for scenarios with fast data changes and narrow application scope. For example, you can save a specific purchase order to the cache.

4. cache call considerations.

The cache has a time limit. When the expiration time set by the server is exceeded, it will be recycled by the server. When the cache is recycled, the corresponding memory block will be cleared. When you access the object through the cache ["cachekey"] Again, the return value is null. Therefore, exceptions may occur in the following calls:

Dataset DS = (Dataset) cache ["cacheds"];

Datarow DR = Ds. Table [0]. Row [0]; // error. DS is null, and Table 0 does not exist.

The correct statement should be:

Dataset DS

If (Cache ["cacheds"]! = NULL)

{

DS = (Dataset) cache ["cacheds"];

}

Else

{

DS = getdsfromdatabase ();

}

 

 

Datarow DR = Ds. Table [0]. Row [0];

How to manage cache in Asp.net

This article states: With my love for English and technology, I have translated articles based on my limited level of English to improve my ability. If anything is wrong, I hope you will give your comments.

Objective: This article describes how to manage the cache and the usage of each cache parameter in Asp.net.

Introduction:

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:Cache data is reused to avoid repeated physical data loading.
Measurable:After the 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 providesKey-ValueFor the corresponding method, the namespace of cache is: system. Web. caching. its lifecycle also depends on the application, but it is not like Session, which is also oriented to 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: Automatically invalidates the cache 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, a change in the cache information 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 from when a 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.4ASP. 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.
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"/>


Note:
Address: http://www.codeproject.com/KB/web-cache/cachemanagementinaspnet.aspx

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.