Go deep into the system. Web. caching namespace and teach you how to hold the Cache Management (3)

Source: Internet
Author: User
Tags connectionstrings visual studio 2010

This article is divided into three parts. Starting from the namespace system. Web. caching where the cache is located, we will introduce in detail the cache classes and operation methods provided by the. NET Framework. After reading this article, you will learn:

  • Article 1-how to implement simple data caching
  • Article 2-cache the data read from the file and timely update the cached data through file dependency
  • Article 3-cache the entire table in the database and timely update of cache data through database Dependencies

After learning the usage of the cache class and cachedependency class in the first two articles, let's take a look at the sqlcachedependency class to update the database cache in a timely manner.

If you have no knowledge about Cache Management, we recommend that you read the first two articles.

 

I. database cache dependency class sqlcachedependency

  The sqlcachedependency class must be used in conjunction with the SQL Server database. Currently, there is no cache dependency for the Oracle database. This article uses SQL server2005 for demonstration.

  1. syntax definition

The syntax of the sqlcachedependency class is defined as follows:

public class SqlCacheDependency: IDisposable

 

Like the cachedependency class, sqlcachedependency also inherits the interface "idisposable", which is mainly used to define how to release allocated unmanaged resources.

The class that inherits this interface must implement the dispone method to release resources. This interface is introduced in the second article and will not be repeated here.

The main constructor of sqlcachedependency is as follows:

public SqlCacheDependency(string dataBase,string table)

Database indicates the database to be enabled, and table indicates the cached table. In actual use, you only need to specify the cached data and tables.

  2. Methods and attributes

The methods and attributes of the sqlcachedependency class are the same as those of the cachedependency class, mainly the three:

  • Attribute "haschanged": determines whether the database dependency has changed.
  • Attribute "utclastmodified": gets the last modification event of the database cache dependency.
  • Method "dispose": releases the resources occupied by the sqlcachedependency object.

The usage of these three members is similar to that of the cachedependency class, so we will not repeat them here. If necessary, refer to article 2.

 

Ii. process using the sqlcachedependency class

  There are two methods I know to implement database cache dependencies. One is to use a programming method, which is similar to the idea of implementing File Cache dependencies in the second article, however, when creating a cache, the dependency is an instance of sqlcachedependency.

So what I want to introduce here isOutputcacheCache Technology. If you want to implement this function programmatically, refer to the final example in the second article.

To implement database cache dependencies, you must combine database operations. Before using the database cache dependency, you must perform the following five steps:

  

 

The database cache dependency can be used normally only when the preceding conditions are met. Finally, let's look at how to implement it.

 

3. Typical applications: Use sqlcachedependency to obtain the latest data in the database table

 

The function of this example is to cache the database table and update the data items stored in the cache to the latest when the content changes.

 

1. Create a database and

Create a database johnconnor_db and add a player table to the database:

  • ID <int> ID of the auto-increment data,
  • Name <nvarchar (20)> player name,
  • Height <nvarchar (10)> player height

 

2. Notify the database to enable cache dependencies.

Sqlserver supports the sqlcachedependency feature and requires related configuration on the database server.

Now let's enable cache notification for the database. There are two ways to notify the database that the table enables cache dependencies,

  • Use the aspnet_regsql command line tool
  • Use the sqlcachedependencyadmin class

First, we will introduce the use of the command line tool, which is located in the Windows \ microsoft.net \ framework \ [version] folder. If you cannot find it, install vs2005 or a later version,

You can click the start/all programs/Microsoft Visual Studio 2010/Visual Studio Tools/Visual Studio 2010 command prompt to use it. In the command prompt box, enter

aspnet_regsql.exe -S 192.168.1.99\sqlserver2005 -U (JohnConnor),-P (JohnConnorV5) -ed -d JohnConnor_DB -et -t Player

 

Note: If the database authentication method is "SQL Server Authentication", replace-E,

If you want to understand the meaning of every command, you can enter aspnet_regsql.exe -? Here we provide a parameter list for your convenience (the list is copied, forgive me for being lazy, amen ~~~)

  • -S is followed by the database server name or IP address;
  • -U is followed by the login username of the database;
  • -P is followed by the database login password;
  • -E use the Windows integrated authentication of the current login user for authentication.
  • -D the following parameter indicates which database adopts the sqlcachedependency function;
  • -C connection string to connect to the database. If you specify the server (-S) and login (-U and-P, or-e) information, this option is not required because the connection string already contains this information.
  • -T followed by the sqlcachedependency function for which table the parameter is used;
  • -Ed allows sqlcachedependency for databases;
  • -Dd prohibits the use of sqlcachedependency for databases;
  • -Et allows sqlcachedependency for data tables;
  • -DT prohibits the use of sqlcachedependency for data tables;
  • -Lt lists the tables in the current database that have used the sqlcachedependency function.

 

Enter the command, press enter, and run successfully. A prompt is displayed, indicating that the database/table is enabled for the SQL cache dependency.

The second method uses the sqlcachedependencyadmin class and directly adds the following registration code under "page_load" on the page.

Protected void page_load (Object sender, eventargs e ){
System. Web. caching. sqlcachedependencyadmin. enablenotifications (
System. configuration. configurationmanager. connectionstrings ["name"]. connectionstring); // notifies the database whose name is the name of the database connection string system. Web. caching. sqlcachedependencyadmin. enabletableforconfigurications (
System. configuration. configurationmanager. connectionstrings ["name"]. connectionstring, "Player"); // notify which table is enabled, and player is the table name}

 

You can.

After the two methods are executed, an aspnet_sqlcachetablesforchangenotification table is added to the database.

 

 

3. Configure database cache items on the website

Then we create an ASP. NET Website (I am lazy, change the name of the second article to continue using...) and name it johnconnor. sqlcachedependencysample.

First, configure the database link string in Web. config:

 <connectionStrings>        <add name="TestDBconnectionStrings" providerName="System.Data.SqlClient" 
      connectionString="Data Source=192.168.1.99\SQLSERVER2005;Initial Catalog=JohnConnor_DB;User ID=JohnConnor;Password=JohnConnorV5;" /> </connectionStrings>

 

Then, add the database cache dependency configuration in the "system. Web" node. Note that the "connectionstringsname" attribute in the configuration must correspond to the name of the previously created database connection string:

  <caching>       <sqlCacheDependency enabled="true" pollTime="1000">           <databases>               <add name="JohnConnor_DB" connectionStringName="TestDBconnectionStrings" pollTime="1000"/>                  </databases>       </sqlCacheDependency>   </caching>

Now, the configuration section is coming to an end. The following describes the acceptance results.

 

4. Completion example

On the default. aspx page generated by default, add a gridview control to display the data obtained from the database. Add a control to display the time and use the time to determine whether the page displays cached data.

First, configure the data source for the gridview, click the task list, and in the "Select data source" drop-down box, click "new data source", and select "Database" in the data source type window of the Configuration Wizard ", click "OK" and the select link string window appears. In the drop-down list, select the "testdbconnectionstrings" connection string we just created, and click "Next". The "Configure SELECT statement" dialog box appears, select "*" in the "column" list box to select all columns, "Next", and "finish ".

Switch to the Code view and add the following in the "page_load" event:

Literal.Test=DateTime.Now.ToString();

It is mainly used to determine whether the display is cached. Now save F5 and refresh the page to see that the time is constantly changing, indicating that the data is not from the cache.

Now add the following code under the "<@ page>" line of the source code view of default. aspx:

<%@ OutputCache Duration="3600"  SqlDependency="JohnConnor_DB:Player" VaryByParam="none"%>

In this way, the database cache dependency is added.

Now F5 runs the website and refresh the page again. The time is no longer changed because the data on the entire page is cached.

Now we modify the following database content and refresh the page. We can see that the time has been pushed backward, and the data has also changed.

This is the role of the database cache dependency.

When the database content is updated, the cached content will be updated no matter whether or not the cache time is reached.

------------------------------------------------------------ End ------------------------------------------------------

The grass has a tail...

So far, the three articles have been completed. This is an end-to-end short series, and it is not easy. Busy. You don't have time to write long articles.

Thank you for your support. Hope to help useful people.

  

 

  

 

 

 

 

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.