Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 100 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
100
Dung lượng
467,28 KB
Nội dung
Lesson 2: Using Caching to Improve Performance CHAPTER 16 943 Lesson 2: Using Caching to Improve Performance ASP.NET caching stores frequently accessed data or whole Web pages in memory where they can be retrieved faster than they could be from a fi le or database. This helps to improve performance and increase scalability (in terms of number of users serviced) of a Web applica- tion. As an example, if you have a product catalog in an e-commerce application, you might consider putting a lot of the catalog data into cache. Data that changes infrequently and is accessed by a lot of users is a good candidate for caching. The fi rst access of this data would load it into the cache; subsequent requests would be served from the cache until the cache expires. ASP.NET and the .NET Framework enable you to take advantage of caching without requir- ing you to write a lot of code to deal with the complexities of caching such as cache expira- tion, updates, and memory management. There are two different types of caching in ASP. NET: n Application caching This represents a collection that can store any object in memory and automatically remove the object based on memory limitations, time limits, or other dependencies. n Page output caching This is ASP.NET’s ability to store a rendered page, portion of a page, or version of a page in memory to reduce the time required to render the page in future requests. This lesson covers both application caching and page output caching. After this lesson, you will be able to: n Use application caching to store frequently accessed data that is expensive to obtain. n Use page output caching to improve the response time of page requests. Estimated lesson time: 40 minutes Application Caching Application caching (also called application data caching) is the process of storing data (and not pages) in a cache object. The cache object is available as a property of the Page object. It represents a collection class of type System.Web.Caching.Cache. The Page.Cache property actually uses an application-wide cache (and not just a page-specifi c cache). This means that a single Cache object exists for your entire application; items in the Cache can be shared between user sessions and requests. This application cache object is managed by ASP.NET for you. Figure 16-15 shows the Cache object. After this lesson, you will be able to: n Use application caching to store frequently accessed data that is expensive to obtain. n Use page output caching to improve the response time of page requests. Estimated lesson time: 40 minutes Estimated lesson time: 40 minutes 9 4 4 CHAPTER 16 Deploying, Configuring, and Caching Applications FIGURE 16-15 The Cache object in System.Web.Caching Using the Cache Object You work with the Cache object like you would Session or similar objects. You can assign items directly to the cache by giving them a name (key) and assigning them an object (value). You retrieve objects from the cache by checking for the given key. It is always wise to verify that the item is not null. If a value is null, that value either hasn’t been cached or it has expired from the cache. If an item is null in the cache, you should have a means to reset it back to the cache (more on this to come). The following code sample demonstrates how to cache and retrieve a String object with the Cache collection: 'VB Cache("Greeting") = "Hello, world!" If Not (Cache("Greeting") Is Nothing) Then value = CType(Cache("Greeting"), String) Else value = "Hello, world!" End If //C# Cache["Greeting"] = "Hello, world!"; if (Cache["Greeting"] != null) value = (string)Cache["Greeting"]; else value = "Hello, world!"; You wouldn’t normally cache a static string in your application; you’d more likely cache a file, a database query result, or other data that is shared and expensive to obtain. You can Lesson 2: Using Caching to Improve Performance CHAPTER 16 945 cache any object type, including your own custom types. However, you must cast the object back to the correct type when you access it from the cache. Inserting Items into the Cache The previous example demonstrates that you can use the Cache object like you would Session or Application. You can access much more sophisticated functionality, however, by using the Add and Insert methods. Each of these methods enables you to add an item to the cache and control how that item gets removed from the cache. This includes automatic removal based on a specific period of time, when a file changes, or another cache object expires. The Cache object has both the Add and Insert methods. The Add method exists to satisfy the collection interface and therefore returns the item added to the cache as a result of the call. This Add method is meant to comply with the collection interface. The Insert method, however, has been the preferred method for adding items to the cache. Both define the same set of parameters and do the same thing behind the scenes. However, Insert has a number of overloads based on the many parameters you can set when adding an item to the cache. The following list outlines the parameters of the Cache.Insert method: n key This is the name (as a String) that you’ll use to access the cached object in the Cache collection. The key must be unique in the cache. n value This is the data (as an Object) that you want to cache. n dependencies A CacheDependency object identifies a file or a key to another item in the cache. When the file or related cached item is changed, this will trigger this cached object to be removed from the cache. If you cache a file, you should configure a dependency for the file so that it is removed from the cache after being modified. This helps ensure that your cache never becomes stale. You might also call the parameter onRemoveCallback to reload the cached item. n absoluteExpiration This is the time (as a DateTime object) at which the object should be removed from the cache. This is absolute and therefore does not take into consider- ation whether the item has been recently accessed by a user. If you do not wish to use absolute expiration, you can set this property to System.Web.Caching.Cache .NoAbsoluteExpiration. n slidingExpiration This is the time (as a TimeSpan object) after which the object should be removed from the cache if it has not been accessed by a user. Set this to System.Web.Caching.Cache.NoSlidingExpiration if you don’t want to use it. n priority This is a CacheItemPriority enumeration value that you can use to determine which objects are removed first when memory starts to run low (this process is called scavenging). Lower priority objects are removed sooner. The values for priority, from lowest (most likely to be removed) to highest (least likely to be removed) include the following: • Low • BelowNormal 9 4 6 CHAPTER 16 Deploying, Configuring, and Caching Applications • Normal (Default is equivalent to Normal) • AboveNormal • High • NotRemovable n onRemoveCallback This is an event handler that is called when the object is removed from the cache. This can be null if you don’t want to specify a callback method. Defining a Cache Dependency A cache dependency links a cached item to something else such as a file or another item in the cache. ASP.NET monitors the dependency and invalidates the cache if the dependent item changes. The following code sample demonstrates how to make a cache dependency based on a file. If the dependent file changes, the object is removed from the cache. 'VB Cache.Insert("FileCache", "CacheContents", New System.Web.Caching.CacheDependency( _ Server.MapPath("SourceFile.xml"))) //C# Cache.Insert("FileCache", "CacheContents", new System.Web.Caching.CacheDependency( Server.MapPath("SourceFile.xml"))); You can also create multiple dependencies for a single cached item. The following example demonstrates how to use an AggregateCacheDependency object to add an item to the cache that is dependent on both an item named CacheItem1 and a file named SourceFile.xml. 'VB Dim dep1 As CacheDependency = New CacheDependency(Server.MapPath("SourceFile.xml")) Dim keyDependencies2 As String() = {"CacheItem1"} Dim dep2 As CacheDependency = New System.Web.Caching.CacheDependency(Nothing, _ keyDependencies2) Dim aggDep As AggregateCacheDependency = New System.Web.Caching. AggregateCacheDependency() aggDep.Add(dep1) aggDep.Add(dep2) Cache.Insert("FileCache", "CacheContents", aggDep) //C# System.Web.Caching.CacheDependency dep1 = new System.Web.Caching.CacheDependency(Server.MapPath("SourceFile.xml")); string[] keyDependencies2 = { "CacheItem1" }; System.Web.Caching.CacheDependency dep2 = new System.Web.Caching.CacheDependency(null, keyDependencies2); System.Web.Caching.AggregateCacheDependency aggDep = Lesson 2: Using Caching to Improve Performance CHAPTER 16 947 new System.Web.Caching.AggregateCacheDependency(); aggDep.Add(dep1); aggDep.Add(dep2); Cache.Insert("FileCache", "CacheContents", aggDep); Setting an Absolute Cache Expiration Many times you want to cache data for a specific amount of time. This allows you to limit the amount of time between cache refresh. To do so, you pass the absoluteExpiration parameter to the Cache.Insert method. This parameter takes a time in the future at which your data should expire. The DateTime.Now object has a variety of methods for adding a specific num- ber of minutes to the current time. The following example demonstrates this: 'VB Cache.Insert("FileCache", "CacheContents", Nothing, DateTime.Now.AddMinutes(10), _ Cache.NoSlidingExpiration) //C# Cache.Insert("FileCache", "CacheContents", null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration); Setting a Sliding Cache Expiration If you want your most frequently used cached objects to stay in your cache longer, you can specify a sliding expiration. A sliding expiration indicates the amount of time that must elapse between subsequent requests before an item is removed from the cache. Each time a new request comes in for a given item, the sliding scale restarts. You set a sliding expiration by passing a TimeSpan to the slidingExpiration parameter of the Insert method. The TimeSpan is the time after the last read request that the cached object will be retained. This example shows you how to keep an object in cache for 10 minutes after the last request: 'VB Cache.Insert("CacheItem7", "Cached Item 7", _ Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration, New TimeSpan(0, 10, 0)) //C# Cache.Insert("CacheItem7", "Cached Item 7", null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0)); You have to be careful with these settings. For example, if you set no absolute expiration but just a sliding expiration, it is possible that heavy usage will result in an item never being removed from the cache (or not for a very long time). It might be wise to use both these properties; the absoluteExpiration can be a fallback if the slidingExpiration never transpires. 9 4 8 CHAPTER 16 Deploying, Confi guring, and Caching Applications Quick Check 1. How can you cause a cached object to be automatically invalidated after a spe- cifi c amount of time? 2. Where is Cache data stored—in memory, on the hard disk, in a database, or on a state server? 3. What types of data can you store in the Cache collection? 4. What must you do before you retrieve an object from the Cache collection? Quick Check Answers 1. Call the Cache.Add or Cache.Insert methods and provide a dependency. 2. The Cache object is stored in memory on the server. 3. You can store any type of data in the Cache collection. However, when you re- trieve it, you must cast it to the correct type. 4. You must verify that the object is not null. If it is null, you must retrieve it from the original source rather than from Cache. Page Output Caching After a Web browser retrieves a page, the browser often keeps a copy of the page on the local computer. The next time the user requests the page, the browser simply verifi es that the cached version is still valid, and then displays the cached page to the user. This improves the responsiveness of the site by decreasing the time required to load the page. It also reduces the load on the server because the server is not required to render a page. Client-side caching requires that each individual user retrieve a dynamically generated version of your page. If one user visits your Web site 100 times, your Web server only has to generate the page once. If 100 users visit your Web site once, your Web server needs to generate the page 100 times. To improve performance and reduce rendering time, ASP.NET also supports page out- put caching. With page output caching, ASP.NET can keep a copy of a rendered ASP.NET Web page in memory on the server. The next time a user requests it—even if it’s a different user—ASP.NET can return the page almost instantly. If a page takes a long time to render (for example, if the page makes multiple queries), this can signifi cantly improve performance. If you have a lot of activity on your server, it can also increase your scalability, as resources used to retrieve data can be freed. If your page shows dynamic information or is customized for individual users, you don’t want the same version of the page sent from the cache to every user. Fortunately, ASP. NET gives you fl exible confi guration options to meet almost any requirement. You can even Quick Check 1 . How can you cause a cached object to be automatically invalidated after a spe- cifi c amount of time? 2 . Where is Cache data stored—in memory, on the hard disk, in a database, or on a state server? 3 . What types of data can you store in the Cache collection? 4 . What must you do before you retrieve an object from the Cache collection? Quick Check Answers 1 . Call the Cache.Add or Cache.Add or Cache.Add Cache.Insert methods and provide a dependency. Cache.Insert methods and provide a dependency.Cache.Insert 2 . The Cache object is stored in memory on the server. 3 . You can store any type of data in the Cache collection. However, when you re- trieve it, you must cast it to the correct type. 4 . You must verify that the object is not null. If it is null, you must retrieve it from the original source rather than from Cache . 1 2 3 4 1 2 3 4 Lesson 2: Using Caching to Improve Performance CHAPTER 16 949 implement user controls to do partial-page caching while generating other portions of the page dynamically. Declaratively Configuring Caching for a Single Page You can configure each ASP.NET page in your site to be cached independently. This gives you granular control over which pages get cached and how they get cached. You manage this by adding the @ OutputCache directive to the top of a page’s markup. You can configure this directive using the attributes shown in Table 16-5. TABLE 16-5 Outpu t Cache Attributes ATTRIBUTE DESCRIPTION Duration The number of seconds to cache the page. This is the only required parameter. Location One of the OutputCacheLocation enumeration values, such as Any, Cli- ent, Downstream, Server, None, or ServerAndClient. The default is Any. CacheProfile The name of the cache settings to associate with the page. The default is an empty string (“”). NoStore A Boolean value that determines whether to prevent secondary stor- age of sensitive information. Shared A Boolean value that determines whether user control output can be shared with multiple pages. The default is False. VaryByParam A semicolon-separated list of strings used to vary the output cache. By default, these strings correspond to a query string value sent with Get method attributes, or a parameter sent using the Post method. When this attribute is set to multiple parameters, the output cache contains a different version of the requested document for each combination of specified parameters. Possible values include none, an asterisk (*), and any valid query string or Post parameter name. Either this attribute or the VaryByControl attribute is required when you use the @ Output- Cache directive on ASP.NET pages and user controls. A parser error oc- curs if you fail to include it. If you do not want to specify a parameter to vary cached content, set the value to none. If you want to vary the output cache by all parameter values, set the attribute to an asterisk (*). VaryByControl A semicolon-separated list of strings used to vary a user control’s out- put cache. These strings represent the ID property values of ASP.NET server controls declared in the user control. 9 5 0 CHAPTER 16 Deploying, Configuring, and Caching Applications SqlDependency A string value that identifies a set of database and table name pairs on which a page or control’s output cache depends. Note that the SqlCacheDependency class monitors the table in a database that the output cache depends on, so that when items in a table are updated, those items are removed from the cache when using table-based poll- ing. When using notifications (in Microsoft SQL Server) with the value CommandNotication, ultimately a SqlDependency class is used to register for query notifications with the SQL Server. VaryByCustom Any text that represents custom output caching requirements. If this attribute is given a value of browser, the cache is varied by browser name and major version information. If a custom string is entered, you must override the GetVaryByCustomString method in your applica- tion’s Global.asax file. VaryByHeader A semicolon-separated list of Hypertext Transfer Protocol (HTTP) headers used to vary the output cache. When this attribute is set to multiple headers, the output cache contains a different version of the requested document for each combination of specified headers. The Location, CacheProfile, and NoStore attributes cannot be used in user controls (.ascx files). The Shared attribute cannot be used in ASP.NET pages (.aspx files). The following example demonstrates how to cache a page for 15 minutes, regardless of the parameters passed to the page: <%@ OutputCache Duration="15" VaryByParam="none" %> If the page might display differently based on parameters, provide the names of those query string parameters in the VaryByParam attribute. The following example caches a dif- ferent copy of the page for different values provided in the location or count query string parameters: <%@ OutputCache Duration="15" VaryByParam="location;count" %> Partial-Page Caching To cache a portion of an ASP.NET Web page, move the portion of the page that you want to cache into an .ascx user control. Then, add the @ OutputCache directive to the user control. That user control will be cached separately from the parent page. Programmatically Configuring Caching for a Single Page If you need to make run-time decisions about output caching, you can do so using the Re- sponse.Cache object. The available programmatic methods do not correspond directly to the attributes provided by the @ OutputCache directive, but they provide basic functionality: n Response.Cache.SetExpires Use this method to specify the number of seconds that the page is to be cached. 9 5 2 CHAPTER 16 Deploying, Configuring, and Caching Applications End Function //C# void Page_Load(object sender, System.EventArgs e) { //specify the callback method. Substitution1.MethodName = "GetCurrentDateTime"; } //the Substitution control calls this method to retrieve the current date and time. //this section of the page is exempt from output caching. public static string GetCurrentDateTime (HttpContext context) { return DateTime.Now.ToString(); } The AdRotator control also performs postcache substitution, by default, to constantly display new ads. Programmatically Invalidating Cached Pages Often, you want to cache pages, but specific events might require you to stop using the cached page. For example, a page that displays results from a database query should only be cached until the results of the database query change. Similarly, a page that processes a file should be cached until the file is changed. Fortunately, ASP.NET gives you several ways to invalidate cached pages. Determining Whether to Return a Cached Page Prior to Rendering To directly control whether a cached version of a page is used or whether the page is dynami- cally regenerated, respond to the ValidateCacheOutput event and set a valid value for the HttpValidationStatus attribute. Then, from the Page.Load event handler, call the AddValida- tionCallback method and pass an HttpCacheValidateHandler object with your method. The following example demonstrates how to create a method to handle the ValidatePage event: 'VB Public Shared Sub ValidatePage(ByVal context As HttpContext, _ ByVal data As [Object], ByRef status As HttpValidationStatus) If Not (context.Request.QueryString("Status") Is Nothing) Then Dim pageStatus As String = context.Request.QueryString("Status") If pageStatus = "invalid" Then status = HttpValidationStatus.Invalid [...]... Site tool to precompile the application Open a page several times, and then view the Trace.axd file to determine how long the first and subsequent requests took with the precompiled application Optimize and Troubleshoot a Web Application For this task, you should complete Practice 1 to learn more about application caching n practice 1 Using the last real-world ASP.NET Web application you created that... one of the most effective ways to improve performance ASP.NET provides two different types of caching: application caching (implemented using the Cache object) and page output caching Application caching requires writing code, but it gives you detailed control over how objects are cached Page output caching keeps a copy of rendered HTML from an ASP.NET page or user control Both types of caching are extremely... reference one site from another site in ASP.NET Lesson 3 1 Correct Answer: C A Incorrect: The Global.asax file is used to define application- level events (and not settings) B Incorrect: The Web.config file will only set settings for Web applications and not W indows applications C Correct: You can use the Machine.config file to manage settings for both Web and W indows applications at the machine level... buttons 2 Correct Answer: B A Incorrect: There is no such button type in ASP.NET B Correct: You create a command button by setting the CommandName property of the button and responding to the Command event for the button C Incorrect: There is no such button type in ASP.NET D Incorrect: There is no such button type in ASP.NET 3 Correct Answer: D A Incorrect: This method will work However, it... In this lab, you configure page output caching for a simple ASP.NET Web application If you encounter a problem completing an exercise, the completed projects are available in the sample files installed from the companion CD in the Code folder E xErcisE 1 enable Page Output caching In this exercise, you enable page output caching for an ASP.NET Web page 1 Open Visual Studio and create a new Web site... CHAPTER 16 Deploying, Configuring, and Caching Applications Answers Chapter 1: Lesson Review Answers Lesson 1 1 Correct Answer: D A Incorrect: The IsCallback property indicates if the page is the result of a callback B Incorrect: The IsReusable property indicates to ASP.NET if the Page object can be reused C Incorrect: The IsValid property indicates if an ASP.NET page passed validation D Correct: The... generated page output is not cached, and future requests might receive the previously cached output n HttpValidationStatus.Valid This causes ASP.NET to return the cached page The following sample demonstrates how to configure your event handler so that it is called when ASP.NET determines whether to use the cached version of the page: 'VB Protected Sub Page_Load(ByVal sender As Object, _ Lesson 2: Using... of the change you made to the OutputCache declaration, ASP.NET caches a separate version of the page for each value of the DropDownList control that you choose, and each expires 10 seconds after it is generated Lesson Summary n You can use the Cache object to store data of any type You can then access the cached data from other Web pages in your application The Cache object is an excellent way to reduce... EventArgs e) { Response.Cache.AddValidationCallback( new HttpCacheValidateHandler(ValidateCacheOutput), null); } ASP.NET calls the method you specify when it determines whether to use the cached version of the page Depending on how you set the HttpValidationStatus in your handler, ASP.NET will use a cached page or a new, dynamically generated version Creating a Cache Page Output Dependency To create... machine level D Incorrect: The Global.asa file was used by classic ASP applications for application- level event handling 2 Correct Answer: B A Incorrect: The Web.config files in the same folder as Machine.config will apply to all Web sites on the machine, not just the current Web application B Correct: The Web.config file at the Web application root will apply only to that Web a pplication C Incorrect: . performance and reduce rendering time, ASP .NET also supports page out- put caching. With page output caching, ASP .NET can keep a copy of a rendered ASP .NET Web page in memory on the server /> < ;asp: DropDownList ID="DropDownListChoice" runat="server"> < ;asp: ListItem>Choice One< /asp: ListItem> < ;asp: ListItem>Choice Two< /asp: ListItem> . /> < ;asp: DropDownList ID="DropDownListChoice" runat="server"> < ;asp: ListItem>Choice One< /asp: ListItem> < ;asp: ListItem>Choice Two< /asp: ListItem>