. Net Petshop4.0 cache design tutorial

Source: Internet
Author: User

Added cache management in Asp.net 2.0:
CacheDependency tracks Cache dependencies. Cache dependencies can be files, directories, or keys with other objects in the application's Cache.

The SqlCacheDependency class monitors specific SQL Server database tables on all supported SQL Server versions (7.0, 2000,200 5) so that when the table is changed, items associated with the table are automatically deleted from the Cache. When the database table is changed, the Cache items are automatically deleted and new versions are added to the Cache. When using SQL Server 2005 databases, the SqlCacheDependency class also supports integration with the System. Data. SqlClient. SqlDependency class. Use the query notification mechanism of SQL Server 2005 to detect data changes that make the SQL query results invalid. Any Cache items associated with SQL queries will be removed from System. Web. Caching. Cache. When using SQL Server 2005, you can use the SqlCacheDependency class to add items that depend on SQL Server database tables or SQL queries to the application Cache.

The AggregateCacheDependency class monitors the collection of dependency objects so that the cache item is automatically removed when any dependency object changes. Objects in the array can be CacheDependency objects, SqlCacheDependency objects, custom objects derived from CacheDependency, or any combination of these objects.

The difference between the AggregateCacheDependency class and the CacheDependency class is that the former allows you to associate multiple dependencies of different types with a single cache item. For example, if you create a page to import data from SQL Server database tables and XML files, you can create a SqlCacheDependency object to indicate the dependencies of the database table, and a CacheDependency to table the dependencies of XML files. You can create an instance of the AggregateCacheDependency class and add each dependency to the class, instead of calling the Cache. Insert method for each dependency. Then, you can use a single Insert call to make the page dependent on the AggregateCacheDependency instance.
For example:
The following is a cache dependency for product in Petshop 4.0. The following is an implementation:
Publicstatic IList <ProductInfo> GetProductsByCategory (string category)
{
Product product = new Product ();
If (! EnableCaching)
Return product. GetProductsByCategory (category );
String key = "product_by_category _" + category;
IList <ProductInfo> data = (IList <ProductInfo>) HttpRuntime. Cache [key];
If (data = null)
{
Data = product. GetProductsByCategory (category );
// Create a AggregateCacheDependency object from the factory
AggregateCacheDependency cd = DependencyFacade. GetProductDependency ();
HttpRuntime. Cache. Add (key, data, cd, DateTime. Now. AddHours (productTimeout), Cache. NoSlidingExpiration, CacheItemPriority. High, null );
      }
Return data;
    }
Introduce Facade mode
In the design of PetShop 4.0, the Facade mode is introduced to facilitate callers to obtain AggregateCacheDependency type objects and introduce the Facade mode.
The Facade mode can be used to encapsulate some complex logics to facilitate callers to call these complex logics. It seems that a uniform facade is provided, which encapsulates internal subsystems into a high-level interface. The purpose of the Facade mode is not to introduce a new function, but to provide a higher level of abstraction based on the existing function, so that the caller can directly call the function without worrying about the internal implementation method. Taking the CacheDependency factory as an example, we need to provide the caller with a simple method to obtain the AggregateCacheDependency object, so we have created the DependencyFacade class:
Publicstaticclass DependencyFacade {
Privatestaticreadonlystring path = ConfigurationManager. Etettings ["CacheDependencyAssembly"];
Publicstatic AggregateCacheDependency GetProductDependency ()
{
If (! String. IsNullOrEmpty (path ))
Return DependencyAccess. CreateProductDependency (). GetDependency ();
Else
Returnnull;
       }
   }
The DependencyFacade class encapsulates the logic for obtaining the AggregateCacheDependency type object. As a result, the caller can call relevant methods to obtain the AggregateCacheDependency type object for creating the relevant dependency:
AggregateCacheDependency dependency = DependencyFacade. GetCategoryDependency ();
Compared to calling the GetDependency () method of the DependencyAccess class directly, in addition to the simpler method, it also judges the CacheDependencyAssembly configuration section. If its value is null, a null object is returned.
CacheDependency factory
The Product, Category, and Item classes that inherit the abstract class TableDependency must create their own objects during the call. Because their parent class TableDependency implements the IPetShopCacheDependency interface, they also indirectly implement the IPetShopCacheDependency interface, which provides a prerequisite for implementing the factory mode. In PetShop 4.0, the configuration file and reflection technology are still used to implement the factory model. In the namespace PetShop. CacheDependencyFactory, DependencyAccess is the factory class for creating IPetShopCacheDependency objects:
Namespace PetShop. CacheDependencyFactory
{
Publicstaticclass DependencyAccess
{
Publicstatic IPetShopCacheDependency CreateProductDependency ()
{  
// Create a PetShop. TableCacheDependency. Product instance and put the cache dependency into AggregateCacheDependency. For details, see TableDependency constructor.
Return LoadInstance ("Product ");
}
// Use the reflection technology to create the entity PetShop. TableCacheDependency. Product instance
Privatestatic IPetShopCacheDependency LoadInstance (string className)
{
// <Add key = "CacheDependencyAssembly" value = "PetShop. TableCacheDependency"/> obtain the assembly name from the configuration file + className to create a CacheDependency instance
String path = ConfigurationManager. Etettings ["CacheDependencyAssembly"];
String fullyQualifiedClass = path + "." + className;
// Using the evispongiven in the config file load the appropriate assembly and class
Return (IPetShopCacheDependency) Assembly. Load (path). CreateInstance (fullyQualifiedClass );
       }
}
}
Build Product CacheDepency
PetShop 4.0 introduces the SqlCacheDependency feature and implements the SQL Cache Invalidation technology for the Cache corresponding to the Category, Product, and Item data tables. When the corresponding data table changes, this technology can remove related items from the cache. The core of this technology is the SqlCacheDependency class, which inherits the CacheDependency class. However, to ensure the scalability of the entire architecture, we also allow designers to establish a custom CacheDependency class to extend cache dependencies. Therefore, it is necessary to create an abstract interface for CacheDependency and configure it in the web. config file.
In the namespace PetShop. ICacheDependency of PetShop 4.0, the IPetShopCacheDependency interface is defined. It only contains one interface method.
Publicinterface IPetShopCacheDependency
{
{
AggregateCacheDependency GetDependency ();
   }
}
The implementation of TableDependency is to create a corresponding SqlCacheDependency type dependency for the Category, Product, and Item data tables.
Publicpolicactclass TableDependency: PetShop. ICacheDependency. IPetShopCacheDependency
{
// Obtain the table separator <add key = "ProductTableDependency" value = "Product, Category"/>
Protectedchar [] configurationSeparator = newchar [] {','};
Protected AggregateCacheDependency dependency = new AggregateCacheDependency ();
Protected TableDependency (string configKey ){
String dbName = ConfigurationManager. AppSettings ["CacheDatabaseName"]; // database name
String tableConfig = ConfigurationManager. Configurettings [configKey];
String [] tables = tableConfig. Split (configurationSeparator );
Foreach (string tableName in tables)
Dependency. Add (new SqlCacheDependency (dbName, tableName ));
       }
Public AggregateCacheDependency GetDependency (){
Return dependency;
       }
}
/// Method to create an instance of Product dependency implementation
/// Create a Product instance because the Product inherits TableDependency
Depending on the dependencies between data tables, the dependencies required for different data tables are also different. The value in the configuration file can be seen. However, no matter how many dependencies are created, the created behavior logic is similar. Therefore, a common class TableDependency is abstracted during design and a constructor with parameters is created, establish the dependency. In the implementation of the interface Method GetDependency (), the returned object dependency is created in a protected constructor. Therefore, the implementation Method here can be seen as the flexible use of the Template Method mode. For example, the child Product of TableDependency builds the SqlCacheDependency dependency of the Product and Category data tables by using the constructor of the parent class:
Publicclass Product: TableDependency
{  
Public Product (): base ("ProductTableDependency "){}
}


/* Optional /*----------------------------------------------------------------------------------------------------------------*/

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.