Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to parse ASP.NET Cache

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to parse ASP.NET Cache, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Abstract

Recently, our system is facing a severe performance bottleneck, which is due to the increase of visits and client requests at the same time, which forces us to solve this problem from two aspects, increase the hardware and improve the performance of the system.

We can optimize our system through a variety of methods, introduce the Cache method to optimize the performance of the system and reduce the burden of the system.

Text

Cache in different locations

Caching is mainly used in Web applications: client browser cache, client and server, and server, so caching can be divided into the following categories:

Client cache (Client Caching); proxy cache (Proxy Caching); reverse proxy cache (Reverse Proxy Caching); server cache (Web Server Caching)

Caching in ASP.NET

There are two types of caches in ASP.NET: output caching and data caching.

Output cache: this is the simplest type of cache, which saves a copy of the page sent to the client, and when the next client sends the same page request, the page is not regenerated (within the cache period), but the page is fetched from the cache; of course, the page will be regenerated because the cache expires or is reclaimed.

Data caching

In addition, there are two special caches: fragment cache and data source cache.

Fragment caching: this is a special output cache, which caches not the entire page, but part of the page; because caching the entire page is usually not feasible, because some parts of the page are customized for users (such as user login information), but we can cache the shared parts of the application, then we can consider using fragment caching and user control caching.

Data source cache: a cache built on a data source control, which includes SqlDataSource, ObjectDataSource, and XmlDataSource controls. Data source caching uses data caching, except that we don't need to deal with caching through display; we just need to set the appropriate properties, and then the data source control can store and retrieve data.

Output cache

The output cache caches the final rendered page. When the client requests the same page again, the control object is no longer recreated, the life cycle of the page is no longer started, and there is no need to execute code again by getting the cached page in the cache.

Now let's design a page so that every time a user sends a page request, it gets the time when the current code executes and displays it on the page.

Figure 1 output cache

This is a simple example. Every time a user sends a page request, the display time of the page is updated. This is because each request gets a new page. In fact, we do not need to respond to each page request in real time. We can cache the page through the output cache whenever the user sends the same page request, and during the cache is valid. The cached page can be returned to the user through the output cache.

To implement the output cache, simply add the following code to the page:

It supports five attributes, two of which Duration and VaryByParam are required

Table 1 output cache properties

Here we set the validity period of the output cache to 23 seconds, that is, when the cache expires, it will be reclaimed; when the user requests the page again, the page will be recreated.

Client cache

Another option is client-side caching, where if the user clicks the "back" button in the browser or re-enters URL in the address bar, the browser will retrieve the page from the cache; however, if the user clicks the "Refresh" button, the cache in the browser will be invalidated and the browser sends a page request.

If we want to use client-side caching, we just need to specify the property Location= "Client" in OutputCache to OK, as shown below:

By adding the Location attribute to the OutputCache, we implement the client cache. By setting the client cache, we can reduce the number of client requests. Someone may ask, "each user * page requests need to be completed by the server, which does not reduce the pressure on the service very well." Indeed, compared with the server cache, the client cache does not reduce the execution of the code and the operation of the database, but when we cache the page containing personalized data in the server, when the client requests the page, because different users have different personalized data, this will lead to request errors. So we can use the fragment cache to cache the common parts or the client cache to cache the user information.

Query String caching

In the previous example, we set the VaryByParam property in OutputCache to None, then the ASP.NET program caches only one copy of the page; if the page request contains query parameters, then during the validity period of the cache, we can only see the cached results, suppose we have a report program that provides users to query relevant product information by product name.

First of all, we create two pages: the query page and the results page. Due to the time constraint, we have designed the page, as shown below:

Fig. 2 report program

First of all, we provide a query page that allows users to query the corresponding finished product information according to the finished product name (ProductName). The specific code is as follows:

Protected void Page_Load (object sender, EventArgs e) {if (! Page.IsPostBack) {/ / Gets product id from table Production.Product. / / Then binding data to drop down list control. InitControl (GetProductId ());}} / Handles the Click event of the btnSubmit control. / Redirects to relative product information page. / / protected void btnSubmit_Click (object sender, EventArgs e) {Response.Redirect (string.Format ("Product.aspx?productname= {0}", ddlProductName.SelectedValue));}

When the user clicks the Submit button, it jumps to the Product page and passes the query parameter, the product name (ProducName), in the Url.

Next, we continue to complete the query page. Since the query parameter ProductName is passed in the previous page, we will query the database according to ProductName to get the corresponding product information. The specific code is as follows:

Protected void Page_Load (object sender, EventArgs e) {/ / Get product name. String productName = Request.QueryString ["productname"]; / / Binding data to data grid view control. InitControl (this.GetData (productName));} / Inits the control. / The dataset. Private void InitControl (DataSet ds) {dgvProduct.DataSource = ds; dgvProduct.DataBind ();} / Gets the data. / Name of the product. / / Returns dataset private DataSet GetData (string productName) {/ / The query sql base on product name. String sql = string.Format ("SELECT Name, ProductNumber, SafetyStockLevel, ReorderPoint, StandardCost, DaysToManufacture" + "FROM Production.Product WHERE ProductNumber=' {0}'", productName); / / Get data from table Production.Product. Using (var con = new SqlConnection (ConfigurationManager.ConnectionStrings ["SQLCONN"]. ToString ()) using (var com = new SqlCommand (sql, con)) {com.Connection.Open (); / gdvData.DataSource = com.ExecuteReader (); / gdvData.DataBind (); var ada = new SqlDataAdapter (com); var ds = new DataSet (); ada.Fill (ds) Return ds;}}

In the previous example, we get the value of ProductName through the property QueryString of Request, then query the database according to ProductName, and * bind the obtained data to the Datagridview control (note: the previous example does not consider the SQL Injection problem).

Figure 3 query results

Now let's add the output cache to the page, as follows:

As mentioned earlier, when the output cache attribute VaryByParam= "None", the ASP.NET program caches only one copy of the page during the cache validity period; now we send the request within the cache validity period (30s).

Figure 4 query results

From the figure above, we find that the query parameter ProductName=BK-M18B-40 is now, but the query result is still the data of ProductName=BB-9108, because the ASP.NET program caches only one copy of the page during the cache validity period.

Through the above example, we found that caching only one page is not applicable to the page output cache containing query parameters; in fact, in the previous example, we only need to change slightly to meet the query parameters, as we all know, we just need to set the VaryByParam property to "*" to OK.

Figure 5 query results

Now the query can get the corresponding results, and if the query parameters are the same as the previous request and the page cache is valid, then the cache will be reused, otherwise, a new page cache will be created.

Since ASP.NET adds an output cache to each query parameter, we should pay attention to whether it is really necessary to cache a copy of the page for each query parameter. Suppose a parameter ProductId is added to the query Url, then there are now two query parameters (ProductName and ProductId) in Url.

Earlier, we set VaryByParam to "*", so the ASP.NET program creates a page cache for both ProductName and ProductId. If we only create a page cache for ProductName, we can modify the VaryByParam, as shown below:

Custom cache control

Earlier, we introduced caching one or more pages through query parameters. In fact, ASP.NET also allows us to customize the cache method to decide whether to cache pages or reuse existing pages. In this case, we can set the VaryByCustom property to achieve this.

Suppose, now that we are going to design a cache based on different UserHostName, because the program first calls the GetVaryByCustomString () method during execution to determine whether to cache the page or reuse the existing one, we can implement the UserHostName-based cache by rewriting this method, as follows:

/ Gets vary cache based on custom string value. / Http context. / / custom string / / public override string GetVaryByCustomString (HttpContext context, string custom) {if (string.Equals (custom, "UserHostName", StringComparison.OrdinalIgnoreCase)) {/ / Indicates that the cache should be vary on user host name. Return Context.Request.UserHostName;} return base.GetVaryByCustomString (context, custom);}

Earlier we overridden the GetVaryByCustomString () method so that when the UserHostName value is different, the corresponding cache value is obtained.

Then let the program create the cache based on UserHostName, so we will add the following code to the page:

By customizing the current GetVaryByCustomString () method, we have implemented different caching methods for Web programs according to UserHostName. In fact, we can also implement more kinds of caching schemes, such as based on user role, time, Url and so on.

Fragment caching

In some cases, we can't cache the entire page, but we still want to cache some pages to reduce the burden on the system; in fact, we can do this in two ways: fragment caching and data caching.

To implement fragment caching, we need to create a custom control cache part of the page, and then we add the OutputCache directive to the custom control so that the entire page will not be cached, with the exception of the custom cache control.

We introduced the use of output cache earlier, just add the OutputCache instruction to the page, suppose we want to add output cache to several pages, which may be easy, but we need to add output cache function in dozens of pages, and in the previous example, the Duration attribute value is directly Hard code to each page, if we need to change the Duration attribute value, then we have to modify each page. ASP.NET also needs to recompile these pages, which is not good for our maintenance and, most importantly, increases our workload.

In fact, we can define an outputCacheProfile (ProductCacheProfile) in the web.config file, then add the CacheProfile attribute to the page and assign the value to the ProductCacheProfile,web.config file as follows:

Now, let's add the CacheProfile property to the page and set it to ProductCacheProfile, as follows:

Data caching

The Cache object is thread-safe: this means that there is no need to explicitly implement locking or unlocking, adding or deleting elements in the Cache object, however, elements in the Cache object must be thread-safe. For example, if we create an entity Product and there are situations where multiple clients may manipulate the object at the same time, we must implement locking and unlocking operations for the entity Product (see "6 implementations of singleton pattern (Singleton) for synchronization").

The cache item in the Cache object is automatically removed: when the cache expires, the dependency is modified or the cache ASP.NET automatically removes the cache item out of memory.

Cached items support dependencies: we can add files, database tables, or other resource types to cached items.

SqlDataSource caching

When we enable caching in the SqlDataSource control, it caches the results in SelectCommand; if there are parameters in the SQL query, the SqlDataSource control caches the results for each parameter value.

This is the same as our previous implementation of the report program caching query pages through the output cache, so we will use the SqlDataSource cache to achieve this effect.

Suppose we want to provide a report program that allows the user to obtain the corresponding product information by selecting the product name (ProductName).

First, we create two data source controls in the page: sourceProductName and sourceProduct, and then bind the data source to Dropdownlist and Gridview respectively. The implementation is as follows:

Now let's query the report program. If the ProudctName has not been cached before, the corresponding cache will be created, and the cached ones will be reused. The query results are as follows:

Figure 6 query results

Cache dependency

Cache dependencies between items

ASP.NET Cache allows us to establish dependencies between caches, that is, one cache item depends on another; the following sample code creates two cache items and establishes dependencies between them. The specific implementation is as follows:

/ / Creates cache object Key1. Cache ["Key1"] = "Cache Item 1"; / / Makes Cache ["Key2"] dependent on Cache ["Key1"]. String [] dependencyKey = new string [1]; dependencyKey [0] = "Key1"; / / Creates a CacheDependency object. CacheDependency dependency = new CacheDependency (null, dependencyKey); / / Establishs dependency between cache Key1 and Key2. Cache.Insert ("Key2", "Cache Item 2", dependency)

Now, when Key1 cache entries are updated or deleted from the cache, Key2 cache entries are automatically deleted from the cache.

File dependence

Earlier, we introduced the dependency between cache items. ASP.NET Cache also provides dependencies between cache items and files, and the corresponding cache items will be invalidated when the file is updated or deleted.

In a DEMO--Weibo Feed introduced in the previous blog post "some summaries of Ajax and JSON", we send requests to Sina Weibo API to obtain corresponding data in real time, but there is a limit on the number of requests within a certain period of time. Once the number of requests exceeds the limit, we will no longer accept requests (for more information, please see Rate-limiting). Therefore, the data can be cached by Cache. When requested by the client, if the cached data already exists, the data will be returned directly, otherwise the Weibo API will request the data again.

First of all, we create a HttpHandler, which is responsible for sending requests to Weibo API and saving the data in the file, * * returning the data to the client.

Figure 7 request process

Next, we define the CacheData () method to save Weibo data to a text file and establish a dependency between the cache and the data file.

/ Caches the data into text file. / The http context private void CacheData (HttpContext context) {/ / Weibo API. String uri = context.Request.QueryString ["api"] + "?" + "source=" + context.Request.QueryString ["source"] + "&" + "count=" + context.Request.QueryString ["count"]; HttpWebResponse response = this.GetWeibos (uri); if (null = = response) {throw new ArgumentNullException ("Response is null");} string jsonData; / / Writes the reponse data into text file. Using (var reader = new StreamReader (response.GetResponseStream (), Encoding.GetEncoding (response.CharacterSet)) {jsonData = reader.ReadToEnd ();} string dataPath = context.Server.MapPath ("weibo.json"); using (var writer = new StreamWriter (dataPath, false, Encoding.GetEncoding (response.CharacterSet) {writer.Write (jsonData);} / / Establishs dependency between cache weibo and text file. / / Sets cache expires after 2 minuntes. HttpRuntime.Cache.Insert ("weibo", jsonData, Dep, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (2);}

Now that we have saved the data to a text file and established a dependency between the cache weibo and the data file, we will return the data in JSON format to the client.

/ Responses the weibo data. / The http contex. Private void ResponseWeibo (HttpContext context) {/ / Gets the weibo cache data. Byte [] buf = Encoding.UTF8.GetBytes (HttpRuntime.Cache ["weibo"] .ToString ()); / / Writes the data into output stream. Context.Response.OutputStream.Write (buf, 0, buf.Length); context.Response.OutputStream.Flush (); / context.Response.Close ();}

Above, we convert the JSON format string to Byte value, then write it to OutputStream, and * * return the data to the client.

/ / The function to get weibo data. LoadWeibo: function () {$.ajax ({/ / Weibo API. Url: "WeiboHandler.ashx", type: "GET", / / NOTE: We get the data from same domain, / / dataType is json. DataType: "json", data: {source: JQWeibo.appKey, count: JQWeibo.numWeibo}, / / When the requet completed, then invokes success function. Success: function (data, textStatus, xhr) {/ / Sets html structure. Var html ='+ 'USER' +': WEIBO_TEXTAGO'; / / Appends weibos into html page. For (var I = 0; I < data.length; iTunes +) {$(JQWeibo.appendTo) .append (html.replace ('WEIBO_TEXT', JQWeibo.ify.clean (data [I] .text)) / / Uses regex and declare DOMAIN as global, if found replace all. .replace (/ DOMAIN/g, DATA [I] .user.domain) .replace (/ USER/g, DATA [I] .user.screen _ name) .replace ('AGO', JQWeibo.timeAgo (DatI [I] .user.domain));})}

Figure 8 request result

Summary

Caching can greatly improve the performance of applications, so it should be considered in the design of applications. This blog mainly introduces the applications and differences between output caching and data caching in ASP.NET.

Page caching is suitable for situations where the generated pages are usually the same or the change time is relatively fixed, for example, if the data is updated every hour, then we can set the duration to 3600s.

Data caching applies to generated pages that are always changing.

This is the end of the answer to the question on how to analyze ASP.NET Cache. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report