Dynamic refresh Cache in ASP.NET

xiaoxiao2021-03-06  121

About us | advertising | Website Business | Contact Us Home    download Document Center Forum  Note   comment View commentary ASP & ASP.NET Site Performance Cache dynamic design of the original use: zhoumj March 31, 2004

ASP & ASP.NET Website Performance Design Cache Dynamic Using Original: Zhou Mengjie Download Article 21 February 21, 2004: Demo.rar

Directory Summary Application Scope and Background ASP Cache Dynamic Using Walkthrough ASP.NET Cache Dynamic Using Cache.add Method Reference Cache With Dynamic Changes Best Implementation Principle Walkthrough Code Summary Reference Author Abstract This article mainly tells how to use Cache technology, To effectively improve website performance. The full text involves two examples, one is based on ASP-based method to use cache in ASP; the other is based on ASP.NET, showing new features used in ASP.NET, especially worth mentioning Database DependenCIES technology, the following will gradually expand the full discussion.

Application range and background of this article suitable for readers:

Familiar with Active Server Page has certain understanding of the .NET architecture. There is a foundation for ASP.NET.

Applies TO: Microsoft® ASP.NET Microsoft® Active Server Page Microsoft SQL ServerTM 2000

The era of informationization has arrived, the more the sprocking bamboo shoots is like the rain. Accordingly, people with professional technicians in the development site are also a lot. Whether developing large sites with separate servers or clusters, or renting virtual space companies, performance (Performance) is an important technical indicator, especially the home page refresh speed. According to statistics, for the end user of the website, if he does not refresh the homepage within 5 seconds, or if there is no refreshing other pages within 10 seconds, most visitors will generate anxiety, and the friendship of the website decline. More seriously, if the website caused by too many access to the number of people (not considering the DOS OR DDOS problem) or an error, the visitor will have a bad impression on the website. Especially the company's image website or a business website for profitability, they have higher requirements for website performance and stability.

There are many factors affecting the performance of the website (such as virtual space or transmission speed, etc.). For developers, there are many techniques and best implementations to improve the access speed of the website, including using stored procedures to improve data query efficiency. Various methods (this article will not be described in one by one), of course, most effective to greatly improve performance by reasonably using Cache.

Cache dynamic using ASP has been released from publishing so far, using ASP technology is quite mature, and since Microsoft launched ASP.NET, it gradually stopped updates to ASP versions. However, because many people are still used to using ASP to develop websites, I will again explain how to use Cache in ASP again.

Simply put the basic principle of using Cache is to continuously save a certain period of time in memory in memory, to provide direct access to it. For example, some data need to be obtained from multiple tables in multiple tables, and almost every page needs to call these data. The best implementation in this case is to bring this part of the data Cache, and the simple implementation of the ASP is to encapsulate the final expression of these data (eg HTML flow) in the string and store it in the ASP built-in object Application (mainly The discussion is dynamic cache, and simple ASP applications are omitted). The advantage of this is that this HTML can be called globally over the entire website, and Application is in memory, so you don't have to query the database, thus speeding up the response time and saving server load. Of course, this is an example of a typical empty time for consumption. Although there are many benefits, it is no longer applicable when there is a frequently changing data source (database), because the ASP Application object has a disadvantage, that is, it is not possible to automatically change with the data source. Change, or control the refresh interval. So developers need to program the dynamic cache. Of course, when the program is designed, you can update the AppLiction when all changes in the data source (database) operation. Thereby, the data source (database) is always consistent. Doing this will be more considered on programming, it is easy to miss the details. So I don't recommend this method in addition to a particular situation.

I think the best way in ASP is to use programmatically refresh Cache, which means that sets an expiration time stored in the Application. Of course, the Application object does not have such an ExpiRetime property in the ASP. This requires the implementation of the program. As in the first example of this article.

Walkthrough preparation: Check if IIS is installed and available, check if SQL Server 2000 is installed and has a default demo database Northwind.

Create a virtual directory in IIS, and pay attention to permission settings, allow Internet anonymous user IUSR_MACHINENAME access. Check the permissions settings for the SQL Server 2000 Northwind database, allow Internet anonymous users IUSR_MACHINENAME to have read permissions to the Categories table. Create three blank demo files in places where virtual directory: default.asp; getcache.asp; conn.asp. DEFAULT.ASP is the front desk page, getCache.asp Controls Cache files in the background, Conn.asp is a file that saves the connection string. Copy the code shown later to these three files. Browse DEFAULT.ASP in IIS, and use the SELECT control to be loaded. It can be seen in a few times a few times. Do not read data from Application within 30 seconds but read data from Application. From the execution effect, the first refresh speed is significantly slower than the rear refresh speed. If there is a condition you can use the SQL Server 2000 Tools "Event Explosion" monitoring "Event Explosion" monitoring will find only the SQL query only when the page is executed.

The basic principle of using this method is to first define a cache variable (which is also stored in the Application object) to store the last and data source synchronization. During each new refresh, it is judged whether the interval between the current time is greater than the time in which the time is greater than the predetermined expiration time. If the cache is not expired, read the HTML stream from the cache, if the cache expires, re-read the data source. And re-write synchronization time, so that Cache is synchronized with the data source.

This method is very popular, but does not do real instant synchronization. Because the changes in the data source in the ASP is difficult or almost impossible to notify the ASP itself. This is also an asp program and J2EE solution is a slight disadvantage. This instant synchronization is achieved on Microsoft's new generation. The following content will focus on how this technology is implemented in ASP.NET. ASP.NET Dynamically uses I am discovered in the .NET Framework in the process of using the ASP.NET. There is a Cache object for special management to store various data objects. This is undoubtedly a big gospel for developers who have previously stored Cache in ASP. The Cache object provides a lot of excellent features, such as setting access priority policies, setting expiration, triggering events when Cache expires, freely managing each record in Cache. But this article I want to focus on how to implement the technique based on data source change event triggers Cache dynamic refresh. First, tell Cache.Add Method.

Cache.Add Method Reference For details, please see MSDN Cache.Add Method. I would like a little bit of explanation [C #] public object Add (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemoved CallbackonRemoveCallback);

KEY is used to retrieve the value of the corresponding value in cache. Object Dependencies that will be stored in Cache can specify an associated file or associated into one other cache. When this file or associated cache changes, this cache is invaliding AbsoluteExpiration specifies absolute expiration Time SLIDINGEXPIRATION Specifies a expired time period priority Specifies the priority of Cache CallbackRemoveCallback When this cache expires, perform the specified entrust function

Cache's best implementation of database dynamic changes to this, our ultimate goal is already clear. That is to implement the objects and methods provided in the .NET Framework to implement Cache to keep instant synchronization with the data source. The breakthrough point is the DependenCIES parameter and the CallbackonRemoveCallback parameter in the cache.add method. The above can be associated with a file or another CACHE. This kind of Cache is invalid if the file or another cache changes, and then triggered the delegate function specified in the CallbackonRemoveCallback parameter to re-refresh Cache.

Therefore, for the data source is a file system file, for example, an XML file, etc., you can specify DEPENDENCIES to specify the actual physical path in the XML file. As shown in the following example code:

Static cache _cache = null; // Declaration global cache variable _Cache

Void Application_Start () {_Cache = context.cache; // Put the cache object in the ASP.NET environment context to _Cache Refreshcache (null, null, 0);}

static void RefreshCache (string key, object item, CacheItemRemovedReason reason) {string strHTML; strHTML = ReadSomeDataFromXML (); // do some processing, such as reading data from the XML file like _cache.Add ( "HTML1", // key strHTML, // stored in the Cache value new CacheDependency ( "C: //CacheDependency//DataSource.xml"), // specify associated file Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback (RefreshCache) // Refresh when Cache fails);} But most data sources are not files, but the data database. This method is not applicable when the database changes, or when certain tables of the database changes. Since files can be associated with cache so that we must find a way to associate the database and a file, which can trigger the file change when some tables are changed, so that the Cache is re-refreshed. According to this idea, it is not difficult to think of two unused technologies for the SQL Server database system: trigger Triggers extended stored procedures Extended stored Province

The principle is as shown above: When data changes in the database table (Update; Delete; Insert) Touch the trigger condition, the trigger performs the extended stored procedure. The extended stored procedure call is a pre-compiled COM component. The function of this COM component is to open a file and then close this file, which causes this file AT (Access Time). Due to the Dependency relationship when cache and this file, the file will cause Cache to be invalid when the file changes. As mentioned above, Cache is invalid, triggered the entrust function, so that the Cache reads data from the database.

Walkthrough is not only included in this example, and involves complicated deployment and system calls, so I will explain step by step. Build a virtual directory in IIS, assume that the actual directory is "c: / cacheDemo", the virtual directory is "cacheDemo". And pay attention to the permission settings, allow Internet anonymous users IUSR_MACHINENAME to access. Check the permissions settings for the SQL Server 2000 Northwind database, allow Internet anonymous users IUSR_MACHINENAME to have read permissions to the Categories table. Create two blank demo files in the place where the virtual directory is created: cachedb.aspx; global.asax; copy the code shown below to the corresponding file and review whether the connection string is correct. Making extended stored procedures COM components. Open Visual Studio.net to create a C new project, select the Extended Stored Procedures DLL in the Visual C Projects -> General File Tree.

The next step specifies the name of the extended stored procedure "XP_Changefileat". Copy the xp_changefileat code of the text to the xp_changefileat of the Proc.cpp file. (Cover the original code in the function). Other files remain unchanged. Compile the program with the Release mode. Copy ChangeFileat.dll to your SQL Server MSSQL / BINN directory. Open SQL Server 2000 Query Analyzer. Select the master database, execute sp_addeXtendedProc 'XP_changefileat', 'ChangeFileat.dll' statement. Sp_addextendedProc is used to load the built-in stored procedure for the extended stored procedure. Add a trigger to the categories of the Northwind database. Select the Northwind database in Query Analyzer, execute the addtrigger.sql of the text. Configure the database, open SQL Server 2000 Enterprise Manager, review various permissions settings. Create blank files, file names: Dependence in c: / cacheDemo, configure permissions, allow SQL Server to have modified permissions, default, no additional configuration. Now deploy and configure completion. Browse cachedb.aspx in IIS to see the expected results. As shown: If there is no correct web page, review each step described above and deeply understand the schematic. If the effect of the above figure occurs, the configuration is correct. Open SQL Server 2000 PROFILER. Whether to read the database when monitoring the refresh page. Since the data is read from the cache, PROFILER should not have any response. This shows that the cache takes effect. Change "Beverages" in the Categories table in SQL Server 2000 Enterprise Manager to "ABCD". Refresh the page again to see if Cache is automatically refreshed. As shown: In the refresh page, see if PROFILER has a response. Since the data is read from the updated Cache, PROFILER should not have any responses. This shows that the cache update takes effect.

Summary here, the most important and most complex examples of this article are finished. Maybe there is a question now, but why do you want to rely on such complex deployment and settings to achieve this effect, .NET does not provide ready-made classes to support databases and cache synchronization? For this problem, I have also happened for a long time. For this reason I also have some inferences, Microsoft launched .Net strategy is to defeat J2EE, whether it is the advanced nature of language or the convenience of development, especially the implementation efficiency of the majority of developers and customers. .NET strives to win a winner. The .NET Framework cache object why the file system is selected to do a Dependence object, becoming a database and cache's link, not a global shared memory, why I also asked Situ Yansan. His explanation is for safety and efficiency considerations.

Everyone knows that if you rely on the global shared memory to do a link between different processes, this method is unsafe, you must be careful, whether reading or writing must be locked, that is, to visit a shared memory Requires LOCK once in Unlock, which also needs LOCK when reading, so frequent locking operations are reduced system performance, and severely produce deadlocks. The advantage of making a link with a file system is that when the text is changed, it is not actually read and write hard drive, but uses the disk cache characteristics of the operating system to transfer to memory. Moreover, by changing the 32-bit integer AT (Access Time), whether or not to modify the file, such a benefit is that in any of the 32-bit operating systems, the 32-bit integer is reading or modifying all the atoms operating. Thereby achieving the purpose of unlocked synchronization. In summary, this method is used to fully utilize the characteristics of the operating system, SQL Server 2000, and .Net, and achieve the best implementation in the implementation of the database and Cache synchronization. Very worth learning from learning.

Code asp: default.asp

<% @ Language = vbscript%> <% option expedition%> <% response.buffer = true%> ASP Cache Demo </ title> <meta http-equiv =" content-type "content =" text / html; charSet = GB2312> </ head> <body > <H4> Refreshing Cache: </ h4> <% response.flush gethtmlstream response.write htmlstream%> </ body> </ html> </ body> </ html> </ body> </ html> </ body> </ html></p> <p>ASP: GetCache.asp</p> <p><% Const CACHE_DEFAULT_INTERVAL = 30 'once every 30 seconds to refresh cache Dim HTMLStream Dim IsExpires IsExpires = CacheExpires Function CacheExpires Dim strLastUpdate Dim result strLastUpdate = Application ( "LastUpdate") If (strLastUpdate = "") Or (CACHE_DEFAULT_INTERVAL <DateDiff ( "s ", strlastupdate, now) Then Result = true setlastupdatetime else result = false end if cacheexpires = result end function</p> <p>Sub setLastupdateTime Application.lock Application ("Lastupdate") = cstr (now ()) Application.unlock End Sub</p> <p>Sub GetHTMLStream If IsExpires Then UpdateHTMLStream End If HTMLStream = Application ( "CACHE_HTMLStream") End SubSub UpdateHTMLStream dim d d = FetchHTMLStream Application.Lock Application ( "CACHE_HTMLStream") = d Application.UnLock End Sub</p> <p>Function FetchHTMLStream Dim rs, strSQL, strHTML Set rs = CreateObject ( "ADODB.Recordset") strSQL = "select categoryID, categoryname from categories" rs.Open strSQL, strConn, adOpenForwardOnly, adLockReadOnly strHTML = strHTML & "<select name =" " SLT_Search ">" While (not rs.eof) strHtml = strHtml & "<option>" strHtml = strHtml & rs.fields ("categoryName") strHtml = strHtml & "</ option>" rs.movenext wend strHtml = strHtml & "</ select>" rs.close set = Nothing fetchhtmlstream = strHtml end function%></p> <p>ASP: Conn.asp</p> <p><! - metadata name = "Microsoft ActiveX Data Objects 2.5 Library" type = "TypeLib" uuid = "{00000205-0000-0010-8000-00AA006D2EA4}" -> <% DIM STRCONN STRCONN = "provike = SQLOLEDB.1 ; Integrated Security = SSPI; Persist Security Info = false; Initial Catalog = Northwind "%></p> <p>C Extended Stored Procedures DLL: Proc.cpp</p> <p>RETCODE __declspec (dllexport) xp_changefileAT (SRV_PROC * srvproc) {// // Make sure an input parameter is present // if (srv_rpcparams (srvproc) == 0) return -1;. // // Extract the file name from the . input parameter // BYTE bType; char file [256]; ULONG ulMaxLen = sizeof (file); ULONG ulActualLen; BOOL fNull; if (srv_paraminfo (srvproc, 1, & bType, & ulMaxLen, & ulActualLen, (BYTE *) file, & fNull) == Fail) Return -1; if (btype! = Srvbigcha "Return -1; file [uLActuallen] = 0; ///////cate the file's time stamp. // char Path [288] =" C: // CacheDemo // "; lstrcat (path, file); HANDLE hFile = CreateFile (path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if CloseHandle (hFile); return 0 (hFile = INVALID_HANDLE_VALUE!) } SQL Server: addtrigger.sql</p> <p>Create Trigger DataChanged On [DBO]. [Categories] for insert, update, delete as exec master..xp_changefileat 'dependnce'</p> <p>ASP.NET: CACHEDB.ASPX</p> <p><% @ Import namespace = "system.data"%> <html> <body> <asp: label id = "author" runat = "server" /> </ body> </ html> <script language = "c #" Runat = "server"> void page_load (object sender, evenetargs e) {string strHtml = (string) cache ["quotes"]; if (strHtml! = null) {author.text = strHtml;} else {author.text = "Server busy";}} </ script></p> <p>ASP.NET: GLOBAL.ASAX</p> <p><% @ Import namespace = "system.data"%> <% @ import namespace = "system.data.sqlclient"%> <script language = "c #" runat = "server"> static cache _cache = null; void application_start ) {_cache = Context.Cache; RefreshCache (null, null, 0);} static void RefreshCache (string key, object item, CacheItemRemovedReason reason) {string mySelectQuery = "SELECT CategoryName FROM Categories"; SqlConnection myConnection = new SqlConnection ( "workstation id = localhost; packet size = 4096; integrated security = SSPI; data source = (local); persist security info = False; initial catalog = Northwind "); SqlCommand myCommand = new SqlCommand (mySelectQuery, myConnection); myConnection.Open () SqlDataReader myReader = mycommand.executeReader (); stringbuilder sb = new stringbuilder (); try {Sb.append ("<select>"); while (MyReader.Read ()) {sb.append ("<option>"); sb.append (myReader.getstring (0)); sb.append ("< / Option> ");} sb.append (" </ select> ");} finally {myReader.close (); myconnection.close ();} _cache.insert (" quotes ", sb.tostring (), New Cachedependency ("c: // cachedemo // dependnce"</p> <p>), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback (RefreshCache));} </ script> References [1] MSDN Supporting Database Cache Dependencies in ASP.NET Jeff Prosise [2] MSDN 25 ASP Tips To Improve Performance and Style Len Cardinal [3] Worx Professional ASP.NET Performance K.Scott Allen</p> <p>About the Author</p> <p>Zhou Mengjie, Beijing University of Technology, School of Computer, 2000, 2003 National Microsoft Innovation Cup Procedural Design Competition Third Prize. Currently served as a studio in the release project. You can contact him via email try@frontfree.net.</p> <p>Copyright Notice</p> <p>The copyright belongs to the original author and the release technology network, reproduced this article must indicate the author and the source: the release technology network.</p> <p>© 2001-2004 All rights reserved. The flying technology team retains all rights to this. © 2001-2004 FrontFree Workgroup. All Rights Reserved. All articles</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-99265.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="99265" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.037</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'pwi_2BH8kiJoxnfOCrFKck5k_2BPAyAgEr_2FLbB0d_2Beow_2BFV8_2FCWk0X5hsz9ktQ5Xc7y6Rmn302VbWhvnGbfr3tQGjQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>