Microsoft enterprise database 4.1 Study Notes (17) cache Module 5 typical usage of Cache

Source: Internet
Author: User

This section describes common methods for developers to use caching. Each method can be used in actual development, with sample code. The first part includes the following usage:

  • Add data to cache, add method, how to add data to cache, set expiration, set priority.
  • Remove Data from Cache
  • Get data from cache, getdata Method
  • Clear cache, flush Method

The second part introduces cache loading.

1.1 add data to the cache

The data to be cached consumes a lot of performance during creation and transmission. For example, in a retailer's application system, some column of product data must be transmitted from the data access component to the User display component before being displayed on the user interface. Represents the entity classes products and orders in the world. To improve performance, some data will be stored in the cache.

You need to add data to the cache, and provide the expiration time for the expiration process. To clear the cache priority, first clear the cache items with lower priority.

Use the add method of cachemanager. If you do not set the expiration time and priority, the default value is automatically set, which is neverexpired and normal. If an item with the same key already exists in the cache, the old item is removed and a new item is added. If this process fails, the cache value will be restored to the original value.

Using system; using system. collections. generic; using system. LINQ; using system. text; using Microsoft. practices. enterpriselibrary. caching; using Microsoft. practices. enterpriselibrary. common; using Microsoft. practices. enterpriselibrary. caching. expirations; namespace beautycode. entlib {public class product {Public String ID {Get; set;} public string name {Get; set;} public decimal price {Get; Set ;}} public class cachetest {public cachetest () {icachemanager manager = cachefactory. getcachemanager (); string id = "11"; string name = ""; decimal price = 100; product Product = new product () {id = ID, kname = Name, price = Price}; manager. add (ID, product, cacheitempriority. normal, null, new s0000ingtime (timespan. fromminutes (5 )));}}}

In the above Code, add data to the cache using the add method, set the priority to normal, no events are activated after expiration, and the expiration time is 5 minutes after the last access.

When deleting an item, the system responds to the deletion event and updates the cache.

In the add method, we can specify a class method that implements the icacheitemrefreshaction interface. When an item is deleted from the cache, the cached data is updated.

[Serializable]    public class ProductCacheRefeshAction : ICacheItemRefreshAction    {        #region ICacheItemRefreshAction Members        public void Refresh(string removedKey, object expiredValue, CacheItemRemovedReason removalReason)        {            throw new NotImplementedException();        }        #endregion    }

If you want to receive the notification of removing cache items, you need to set parameters in the add method.

Manager. Add (ID, product, cacheitempriority. Normal, new productcacherefeshaction (), new slidingtime (timespan. fromminutes (5 )));

Key points:

  • You can use unity to create an object instance.
  • If an item is added to the cache configured to use the database as the backend storage, the added item must be serializable and the serializable attribute must be added.
  • When the database is used as the backend storage, the class implementing icacheitemrefreshaction must be serializable to add the serializable feature.

1.2 delete items from the cache

Based on the scan policy and expiration Policy set when an item is added, the scanning and expiration processes automatically delete the item from the cache. You can also manually remove some items.

 

 

Public void remove (cachemanager cache, string key)
{
Cache. Remove (key );
}

 

1.3 obtain data from the cache

Use the getdata method of cachemanager

 

 

Public t getdata <t> (cachemanager cache, string key)
{
Return (t) cache. getdata (key );
}

 

1.4 clear Cache

By using the flush method of cachemanager, all items in the cache will be cleared, whether or not they have expired.

 

 

Public void flush (cachemanager cache)
{
Cache. Flush ();
}

2. load data to the cache

Before obtaining data from the cache, you must add some data to the cache. You can load data in two ways:

  • One-time loading: load the required data to the cache at a time to facilitate later loading.
  • Load data to the cache only when a data request occurs.

2.1 one-time loading

When the application starts, the required data is loaded at one time.

Advantages:

Because you can ensure that the data has been loaded into the cache, theoretically you do not need to judge the cache status. However, before obtaining data, you must check whether the data exists in the cache, because the cache may be cleared.

Because you use the cache, the performance of the application will be improved, and the application response will be faster.

Disadvantages:

All data is cached at one time, which does not greatly improve the system performance, because the data that takes time to cache includes unnecessary data. If the application processes 100 requests, and only one request is processed after the login, other cached requests are unnecessary.

Recommended one-time Loading Method

When a large amount of data is stored at home during application startup or initialization, it is best to use background threads for asynchronous loading. If you do not use the one-time loading method correctly, your application will be slow during initialization. One-time loading is recommended in the following scenarios.

  • Controllable lifecycle of loaded data
  • Control the volume of loaded data. If you do not know how much data to load, you may exhaust system resources.

2.2 load data based on requests

Advantages:

During application initialization, system resources are not exhausted because a large amount of data is not loaded. You do not need to load unnecessary data.

Disadvantages:

When used, the performance may decrease a little because the requested data may not be cached, but is obtained from the data source and then cached. Before obtaining data from the cache, you also need to check whether the data already exists in the cache. This check may include excessive conditional logic in your code.

Recommended Method for loading data based on requests

  • You need some data, but no resources are loaded to save all the data.
  • The data you need cannot be loaded when initializing the system. For example, the data may be related to user input items, such as user information.

Code example for loading data to the cache at one time

Code

Public list <product> getproductlist ()
{
Return new list <product> ();
}
Public void loadallproducts ()
{
Icachemanager manager = cachefactory. getcachemanager ();
List <product> List = getproductlist ();
Foreach (product P in List)
{
Manager. Add (P. ID, P );
}
}

 

 

The following is a sample code for loading data to the cache according to the request.

 

 

Code

Public Product getbyid (string productid)
{
Return New Product ();
}
Public Product readproductbyid (string productid)
{
Icachemanager manager = cachefactory. getcachemanager ();
Product P = (product) manager. getdata (productid );
If (P = NULL)
{
P = getbyid (productid );
If (P! = NULL)
Manager. Add (productid, P );
}
Return P;
}

 

 

First, check whether there are items with the same key in the cache. If not, obtain the items from the data source, add them to the cache, and return data.

Not complete ................................

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.