Server-side data caching

Một phần của tài liệu fast asp.net websites (Trang 191 - 194)

ASP.NET– specific techniques

12.1 Server-side data caching

This may be the final chapter in this book, but it covers one of the most important aspects of the performance of a web application: server-side data caching. Most appli- cations on the web will work with frequently used data that isn’t updated all that often.

This makes it a prime candidate for data caching. For example, you may retrieve a list of country names from the database that doesn’t change often, or you may retrieve a list of default settings that only changes once every six months. These chunks of data are perfect candidates for data caching, and you can speed up your application con- siderably by adding them into a cache.

Figure 12.1 shows caching can be applied to layers in the application. If used effectively in each layer in your application, caching can make your application extremely fast.

Fortunately, caching doesn’t extend only to databases. You could cache the result of a call to a web service or even a long-running code calculation. If code is called fre- quently but the returned result doesn’t change often, it’s ideal for caching. Because the data is retrieved from memory, it’s often returned instantly.

12.2 System.Runtime.Caching

The .NET Framework has a built-in set of classes that fall under the System.Run- time.Caching namespace. This namespace contains types that let you implement an in-memory cache in your .NET Framework applications. The cache object enables you to store everything from simple name/value pairs to more complex objects, such as datasets and entire web pages. The classes are also extensible and if you’re looking for more flexibility, they allow you to create custom caching providers. The built-in classes that fall under the System.Runtime.Caching namespace are easy to implement and can produce impressive results.

You’ve been working with the Surf Store application throughout this book. Now you will learn how easy it is to add caching to any ASP.NET application and improve its web page load times. To get started, you need to add a reference to the System.Run- time.Caching library in your project.

Figure 12.1 Caching can be applied to different layers of your application.

173 System.Runtime.Caching

In figure 12.2, a reference to the System.Runtime.Caching namespace is added to start caching in the sample application. Because you’re going to add caching in the sample application’s data layer, I’ve added the reference to the SurfStoreApp.Data project.

A few simple methods like the ones shown in the next listing are enough to get started caching.

ObjectCache cache = MemoryCache.Default;

/// <summary>

/// Adds the item into cache.

/// </summary>

/// <param name="key">The key used as a reference</param>

/// <param name="objectToCache">The object to cache.</param>

public void AddItem(string key, object objectToCache) {

_cache.Add(key, objectToCache, DateTime.Now.AddHours(6));

}

/// <summary>

/// Retrieves the item from cache /// based on the key passed in.

Listing 12.1 Basic methods to add and retrieve items from cache Figure 12.2 A reference to System.Runtime.Caching added to your application

Initializes a new instance of the MemoryCache class.

Accepts the key and the object to cache as parameters.

Adds the object into the cache for 6 hours.

/// </summary>

/// <param name="key">The key.</param>

/// <returns></returns>

public object RetrieveItem(string key) {

object objectRetrievedFromCache = cache.Get(key);

return objectRetrievedFromCache;

}

The first line initializes a new instance of the MemoryCache class, and you reference to the default MemoryCache instance. The MemoryCache object is flexible and allows mul- tiple instances inside a single application.

A method allows you to add an item into cache with a key, which you use to retrieve the object from cache when required. It’s worth mentioning that MemoryCache is not as strict as dictionary-based collections; if you request an item key that doesn’t exist, you’ll get a null rather than a runtime error.

When you’re building your application, you might come across a scenario in which similar objects have similar names. If that happens, consider building a dynamic key string to identify your objects. If you try to add an object into the cache and a key with the same name already exists, the new object will overwrite the older one.

The code in the previous listing is effective, but it could be rewritten so it’s easier to reuse and so it takes a dynamic key into account. The following listing is a more effective data caching class you can use throughout your application.

public class DataCaching {

static readonly ObjectCache Cache = MemoryCache.Default;

/// <summary>

/// Retrieve a cached item /// </summary>

/// <typeparam name="T">Type of cached item</typeparam>

/// <param name="key">Name of cached item</param>

/// <returns>Cached item as type</returns>

public static T Get<T>(string key) where T : class {

if (Cache.Contains(key)) {

return (T)Cache[key];

}

return null;

}

/// <summary>

/// Insert value into the cache using /// appropriate name/value pairs /// </summary>

/// <typeparam name="T">Type of cached item</typeparam>

/// <param name="objectToCache">Item to be cached</param>

Listing 12.2 Adding and retrieving items from cache

Retrieves the object from cache based on the passed in key.

Initialize a new instance of the MemoryCache class.

Reusable method retrieves an item from cache based on a key. It also returns it in the specified typed, so there’s no need to cast farther down the chain.

Check to see if the cache contains the object based on the key.

175 The sample application

/// <param name="key">Name of item</param>

public static void Add<T>(T objectToCache, string key) where T : class {

Cache.Add(key, objectToCache, DateTime.Now.AddDays(30));

}

/// <summary>

/// Remove item from cache /// </summary>

/// <param name="key">Name of cached item</param>

public static void Clear(string key) {

Cache.Remove(key);

}

/// <summary>

/// Gets all cached items as a list by their key.

/// </summary>

/// <returns></returns>

public static List<string> GetAll() {

return Cache.Select(keyValuePair => keyValuePair.Key).ToList();

} }

This code can be used throughout your application to cache data and retrieve differ- ent object types from cache. It contains a set of useful dynamic methods and should cover the basic caching needs of an application.

Một phần của tài liệu fast asp.net websites (Trang 191 - 194)

Tải bản đầy đủ (PDF)

(210 trang)