ASP.NET database Coke-dependent
By Peter A. Bromberg, ph.d.
In ASP.NET, the Cache class is the coolest feature is that it can control your own behavior based on a variety of dependence. Based on file-based dependenable, the file-dependent is added by using cache.insert and provides a cachedependency object of the reference file.
Cache.insert ("MyData", Source, New Cachedependency (Server.MAppath))))));
But when we want the cache to fail according to the change in the database and rebuild the cache, this scenario exists in many applications. ASP.NET does not provide internal direct cache support for changes in monitoring database tables. Using SQL Server's uncommon system stored procedure sp_makewewebtask, this stored procedure is originally used as generating a web page from the query, but we use it slightly - use it in the trigger, we will A reasonably and effective way can be achieved, and a specific file is modified when the database is updated, deleted or modified, which will make the file monitoring process in the CachePendency instance detected the change of the file, so that Cache invalidation. In fact, because the Cachedependency class works on the UNC file protocol, we can deploy this solution throughout the Web Farm. Applications on each machine on Web Farm will pass the UNC file path to monitor a single machine in WebFarm. Same file
Less nonsense, let us create a simple web application to demonstrate it if it works. First, we will use the Northwind sample database trusted in our SQL Server. Create a simple DataGrid to display records in the Employees table. The first thing we have to do is create a trigger.
Create Trigger
Writecachedepfile
On
[dbo]. [employees]
For INSERT, UPDATE, DELETE
AS
EXEC SP_MAKEWEBTSK '//PETER/C (Cache/mycache.txt', 'SELECT TOP 1 Firstname from Employees'
The above stored procedures are simply telling SQL Server. If any changes occur in the Employee table, based on a simple query, this simple query statement is actually enough, as long as it is a valid T- SQL statement, SQL Server will be happy to update that file.
Next, we need to create a directory and set it to sharing. You may want to update the file's access to allow it to be written, pay attention, I am using the administrator sharing "C $" here. In addition, you need to create an empty text file, "mycache.txt" .
Ok, you can now create our app. First, enter the relying on the file name in the web.config file, so that we do not need to re-deploy the application when modifying the dependencies.
Add AppSettings Configuration Sections on the root of Web.config files:
appsettings>
configuration> Now let us build a caching mechanism in the Global class so we don't need to write specific code in any page.
[C #]
Public Class Global: System.Web.httpApplication
{
Cache _Cache = NULL;
Public static bool blnreflash = false;
Public const string connStr = "Server = localhost; database = northwind; uid = sa; pwd ="
Public const string strsql = "SELECT EMPLOYEID, LastName, Firstname from Employees";
Protected void Application_Start (Object Sender, Eventargs E)
{
_Cache = context.cache;
Refreshcahe (NULL, NULL, 0);
}
Protected Void Session_Start (Object Sender, Eventargs E)
{
IF (httpContext.current.cache ["Employees"] == null)
Refreshcache (NULL, NULL, 0);
}
Static void refreshcache (String Key, Object Item, CacheItemRemovereason REASON)
{
SqlDataAdapter Adapter = New SqldataAdapter (strsql, connStr);
DataSet DS = New DataSet ();
Adapter.Fill (DS, "Employees");
CacheitemoverovedCallback onremove = new cacheItemRemovedCallback (Refreshcache);
String depfile = configurationSettings.appsettings ["dependencyfile"]. TOSTRING ();
HttpContext.current.cache.insert ("Employees", DS, New CachedPependency (depfile),
Cache.NoabsoluteExpiration, cache.noslidingexpiration,
CacheItemPriority.high, onremove;
BLNREFLASH = TRUE;
}
}
Just as I saw above, we defined a Cache type _Cache object, in the Application_Start method, we assume the current Cache instance to it, then call the refreshcache method to fill the object. Refreshcache is actually a static delegate callback method, which is made to make a DataSet from the Empoyees table, then create the CacheItemRemoveDCallback type delegate OnRemove to point to the refreshcache method, so when the monitored file changes, This delegate, refresh the data in the cache is called when the cache is invalid.
Finally, we insert DataSet into the cache along with the OnRemove commission. In session_start, for "insurance", I additionally add a judgment to call the refreshcache method to fill the cache.
Here, our app is created, and you can access the cache DataSet in any page. In Webform1ASPX, I demonstrate how to use it. [C #]
Private Void Page_Load (Object Sender, System.EventArgs E)
{
/ / Ensure that the cache is not empty, if it is empty, fill it
IF (cache ["Employees"] == NULL)
Global.refreshcache (NULL, NULL, 0);
CacheStatus.text = "Cache Refreeshed AT" DateTime.now.tolongTimeString ();
Else
CacheStatus.text = "Dataset from Cache";
DataSet DS = (Dataset) Cache ["Employees"];
DataGrid1.datasource = DS.TABLES [0];
DataGrid1.databind ();
}
Now, if you request this page, it will show a Dataset from cache, if you keep your browser open, open the SQL Server query analyzer, select the Northwind database, execute SQL statement 'Update Employees Set lastname = 'Davovlieu' Where EmployeeID = 1 ', update the record in the table, then reclaim the page, you will see the cache has been invalidated and refreshed.
Translator Press: About database-based cache dependencies, there is also a DataSet implementation (Rob Howard implementation) ASP.NET Cache Invalidation on Database Change on DataSet (Rob Howard) ASP.NET Cache Invalidation on Database Change,
At present, there is no very natural solution in ASP.NET1.1, which is worth gratifying. Asp.net2.0 released with Whidbey, there is YUKU, providing a nice implementation from the data layer. let us wait and see!
The following project is Visual Studio.net 2003 format.
Download this article