20 tips for ASP. net mvc 3 development (20) [20 recipes for programming MVC 3]: loading of cache results data accelerated pages

Source: Internet
Author: User
Tags connectionstrings

Topics

With the development of the website, a large number of users access popular content and dynamic content. These two factors will increase the average loading timeWebThe server and database server cause a lot of request pressure. A large number of data requests require powerful database processing capabilities. ImprovedProgramWith minimal unnecessary database access or dynamic processing of requests, you can save the cost of adding more servers and significantly improveWebThe overall speed of the application.

 

Solution

ImplementationOutputcacheattributeClass, the data or relatively fixed actions that are not frequently changed in the cache.

 

Discussion

InMvc3It is very easy to implement caching. Add the following attributes to the action of a controller:

 

 
[Outputcache (duration =600)]

 

This statement will automatically cache this view600Second (or10Minutes. This means thatCodeWhen you have1000When a user accesses this page at the same time, only one data load is required to save thousands of database requests andIISHandle the load.

 

The output cache attribute looks very simple, but when you open the hood, you may also find that the engine of this car is so complicated. Unless you are a mechanic. This attribute provides a lot of caching methods, which must last for caching, and even addSQLDependencies, which we will discuss in depth.

 

It is very easy to cache by time, you just need to tellMVCHow many seconds should the view be cached. As for the cache storage location, whether it is a client browser or a server or their combination, this problem is a little complicated. A good practice is to analyze the cached content data first. It is more appropriate to cache data shared by multiple users on the server. However, if it is personal data, for example, it is better to cache a custom webpage in your browser. Although caching is a great invention, it also has limitations. Generally, the Maximum Cache limit is the memory, not everything can be cached on the server.

 

However, the most interesting way isSQLDependency.OutputcacheIt is a very useful function to allow data to be cached until its content changes in the data. Take books as an example. new books are not frequently added. Therefore, you can set a cache time for books (for example24Hours ). However, if you have added a new book before the cache expires, or you haven't added a new book for a long week or a few days? In the first case, adding a new book cannot appear in time, and users will be unhappy. In the second case, because no new books are added, unnecessary server requests are initiated every day. UseSQLAs we hope, the cache can be updated immediately when the book table changes.

 

This is a great feature, in otherProgramming Language, You need to manually control the cache, You need to manually update the invalid cache. Believe me, this will easily lead you to miss one or two caches that should be cleared normally.

 

In the following example, the book list page is cached. By defaultVarybyparamValue,Mvc3A unique cache object is automatically created. This is a great feature. In the example in this book, the search keyword is also used as one of the input parameters, but hundreds of different keyword combinations may be input, therefore, this variable should not be cached (this is the problem that the above increase will generate a memory warning ). The following changes enable the cacheBookscontrollerController:

 

 Using System;
Using System. Collections. Generic;
Using System. Data;
Using System. Data. entity;
Using System. LINQ;
Using System. LINQ. Dynamic;
Using System. Web;
Using System. Web. MVC;
Using Mvcapplication4.models;
Using Mvcapplication4.utils;
Using Pagedlist;
Namespace Mvcapplication4.controllers
{
Public Class Bookscontroller: Controller
{
Private Bookdbcontext DB = New Bookdbcontext ();
//
// Get:/books/
[Outputcache (duration = 600 , Varybyparam =
" Sortorder; filter; Page " )]
Public Viewresult index ( String Sortorder,
String Filter, String Keyword, Int Page = 1 )
{
...
Return View (books. topagedlist (currentpage,
Maxrecords ));
}
...
}

}

 

This code is a very good cache solution that can immediately reduce server load. Next, extend this exampleSQLBefore you start to work, you must make some settings. First, modifyWeb. config, Define a database link in the file, and thenSQLThe dependency settings are as follows:

 

 <?  XML version = "1.0"  ?> 
< Configuration >
< Connectionstrings >
< Add Name = "Applicationservices" Connectionstring =
"Data Source =. \ sqlexpress; Integrated Security = sspi;
Attachdbfilename = | datadirectory | aspnetdb. MDF;
User instance = true" Providername = "System. Data. sqlclient"
/>
< Add Name = "Booksdbcontext" Connectionstring =
"Server =. \ sqlexpress; database =
Mvcapplication4.models. bookdbcontext;
Trusted_connection = true" Providername =
"System. Data. sqlclient" />
</ Connectionstrings >
...
< System. Web >
< Caching >
< Sqlcachedependency Enabled = "True" Polltime = "2000" >
< Databases >
< Add Name = "Mvcapplication4.models. bookdbcontext"
Connectionstringname = "Booksdbcontext" />
</ Databases >
</ Sqlcachedependency >
</ Caching >
...
</ System. Web >
...
</ Configuration >

 

In the preceding examplePolltimeSet2000Millisecond, that is, every2In seconds, it will query whether the cache database is changed once. This variable setting can be modified according to your actual needs.

 

Now, you need to modifyGlobal. asax. CSFile, must be inApplication_startTheSqlcachedependencyadminClassEnabletableforpolicicationsMethod to add the listening function for each table to be cached.

 

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using System. Web. Routing;
Using Mvcapplication4.models;
Using System. Data. entity;
Using System. Globalization;
Using System. Threading;
Using Mvcapplication4.utils;

Namespace Mvcapplication4
{
Public Class Mvcapplication: system. Web. httpapplication
{
...
Protected Void Application_start ()
{
Database. setinitializer <bookdbcontext> (
New Bookinitializer ());

Arearegistration. registerallareas ();

Registerglobalfilters (globalfilters. filters );

Registerroutes (routetable. routes );

String connectionstring =
System. configuration. configurationmanager. connectionstrings
[ " Booksdbcontext " ]. Connectionstring;

System. Web. caching. sqlcachedependencyadmin.
Enablenotifications (connectionstring );

System. Web. caching. sqlcachedependencyadmin.
Enabletablefornotifications (connectionstring, " Books " );
}
...
}

}

In the command line window, perform the following stepsSQLNotification function Configuration:

 

Click Start and select Run"

Enter"CMDAnd press Enter.

Cd % WinDir % \ microsoft. Net \ framework \ v4.0.30319 \ aspnet_regsql.exe-S. \ sqlexpress-ed-DMvcapplication4.models. bookdbcontext-et-T books-e

 

Replace the server name, database name, and table name in the command with your own information. In addition, if your database contains a user name and password, additional input parameters (-UAnd-P). After the command is run, two successful messages are displayed. The first one indicates that the database cache function is enabled, and the second one indicates that the specified table cache is successful.

 

Finally, useSQLDependent cache needsBookscontrollerMake a slight modification. In addition, because the application cache mode is changed, the cache duration previously set must be changedInt32.

 Using System;
Using System. Collections. Generic;
Using System. Data;
Using System. Data. entity;
Using System. LINQ;
Using System. LINQ. Dynamic;
Using System. Web;
Using System. Web. MVC;
Using Mvcapplication4.models;
Using Mvcapplication4.utils;
Using Pagedlist;

Namespace Mvcapplication4.controllers
{
Public Class Bookscontroller: Controller
{
Private Bookdbcontext DB = New Bookdbcontext ();
//
// Get:/books/
[Outputcache (duration = int32.maxvalue, sqldependency =
" Mvcapplication4.models. bookdbcontext: Books " ,
Varybyparam = " Sortorder, filter, page " )]
Public Viewresult index ( String Sortorder, String Filter,
String Keyword, Int Page = 1 )
{
...
Return View (books. topagedlist (currentpage,
Maxrecords ));
}
...
}
}

 

In the previousMVCIn the version, local cache is not supported, which means that the results of the entire action must be cached every time. CurrentlyMvc3Local cache is supported in the version. To implement this function, you need to create a secret similar1.14Used inAjaxAutomatically submit the form. InBookcommentscontrollerThese two activities are returned to the Division view, without the need to cache the cached content in the parent action. This is a great improvement. You can effectively isolate your code from the cache content that is not frequently changed.

 

Reference

outputcacheattribute sqlcachedependencyadmin original book address books Source Code

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.