Use of Asp. Net Core cache, asp. netcore

Source: Internet
Author: User
Tags delete cache actionlink

Use of Asp. Net Core cache, asp. netcore

Original article: http://www.binaryintellect.net/articles/a7d9edfd-1f86-45f8-a668-64cc86d8e248.aspx
Environment: Visual Studio 2017, Asp. Net Core 1.1.

The cache mechanism is mainly used to improve performance. In ASP. NET Web Forms and ASP. net mvc, you can directly use the cache object to cache data. This is usually called "server-side cache" and is a built-in feature of the Framework. Although Asp. Net Core does not have such a cache object, it can easily implement the cache function. This article will introduce this.

Before proceeding, use the Web Application project template to create an Asp.net Core Application:

Note: To use the cache function, you must install the "Microsoft. Extensions. Caching. Memory" extension package through NuGet. Reference: using Microsoft. Extensions. Caching. Memory;
1. Enable the cache function in the Startup class.

As mentioned above, Asp. Net Core does not have built-in cache objects, so they cannot be used in the Controller. To use the memory cache in Asp. Net Core, you must rely on the injection (DI) memory cache service (in-memory caching service) in the Startup class ). Open the Startup File and modify ConfigureServices () as follows:

public void ConfigureServices(IServiceCollection services){    services.AddMvc();    services.AddMemoryCache();}

The AddMemoryCache () method adds the memory cache function to the Service set.

2. Inject cache objects into the Controller

Modify HomeController as follows:

public class HomeController : Controller{    private IMemoryCache cache;    public HomeController(IMemoryCache cache)    {        this.cache = cache;    }    ...}

Using constructors to inject cache objects, we have available cache variables in the controller.

3. Use the Set () method to cache an object

With the IMemoryCache object, you can easily read or write cache data.

public IActionResult Index(){    cache.Set<string>("timestamp", DateTime.Now.ToString());    return View();}

The above Code uses the Set <T> () method of IMemoryCache to add a record to the cache. The first parameter of the Set () method is the cache name, and the second parameter is the value.

4. Use the Get () method to obtain the cache

Once you have added the cache, you can Get them through the Get () method.

public IActionResult Show(){    string timestamp = cache.Get<string>("timestamp");    return View("Show", timestamp);}

The code above demonstrates how to obtain data from the cache. The Get () method specifies the cache name and the returned data type.

The following shows the obtained cache:

Run your application and open/Home/Index. a timestamp is generated and saved to the cache. Enable/Home/Show to check whether timestamp data has been obtained from the cache. The/Home/Show page is displayed as follows:

5. Use the TryGet () method to check whether a specified cache item exists.

In the preceding table, a new timestamp is generated and cached for each access to/Home/Index. This is because no cache entry with the same name exists. There are two ways to detect cache items with the same name:

//first wayif (string.IsNullOrEmpty(cache.Get<string>("timestamp"))){    cache.Set<string>("timestamp", DateTime.Now.ToString());}//second wayif (!cache.TryGetValue<string>("timestamp", out string timestamp)){    cache.Set<string>("timestamp", DateTime.Now.ToString());}

The first method still uses the Get () method. If the value cannot be obtained, IsNullOrEmpty () is returned ().

The second method is more elegant. You can use TryGet () to obtain the value. The TryGet () method returns a Boolean value indicating whether a cache item exists. The actual cache value is obtained through the out parameter.

6. Use GetOrCreate () to add non-existent cache items

You may have this requirement. If a cache item exists, it is retrieved. If it does not exist, it is created. In this case, you can use the GetOrCreate () method:

public IActionResult Show(){    string timestamp = cache.GetOrCreate<string>("timestamp", entry => {        return DateTime.Now.ToString();    });    return View("Show", timestamp);}

Use the GetOrCreate () method to check whether timestamp exists. If yes, assign a value to the local variable. Otherwise, create a new cache item.

Visit the/Home/Show page and you can see that the timestamp is displayed. Timestamp is not assigned a value through/Home/Index.

7. Set the resolution and sliding period of the cache

In the previous display column, cached data exists until the Remove () method is called. You can also set the absolute duration and sliding duration for the cache. The absolute duration is to set a specific expiration time for the cache, And the sliding duration is the amount of idle time to remove the cache.

You can set the cache duration policy through the MemoryCacheEntryOptions object:

public IActionResult Index(){    //cache.Set<string>("timestamp", DateTime.Now.ToString());    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();    options.AbsoluteExpiration = DateTime.Now.AddMinutes(1);    options.SlidingExpiration = TimeSpan.FromMinutes(1);    cache.Set<string>("timestamp", DateTime.Now.ToString(), options);    return View();}

The code above creates the MemoryCacheEntryOptions object in Index () action, and sets a policy with an absolute duration of 1 minute and a sliding duration of 1 minute. The MemoryCacheEntryOptions object is passed as the third parameter of the Set () method.

8. Define the callback function after the cache is removed.

Sometimes you may need to be notified after the cache is removed. There are two reasons for the cache to be removed: one is to call the Remove () method, and the other is to automatically Remove the cache after expiration. You can get the notification after removing the cache by setting the callback function:

public IActionResult Index(){    //cache.Set<string>("timestamp", DateTime.Now.ToString());    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();    options.AbsoluteExpiration = DateTime.Now.AddMinutes(1);options.SlidingExpiration = TimeSpan.FromMinutes(1);options.RegisterPostEvictionCallback(MyCallback, this);    cache.Set<string>("timestamp", DateTime.Now.ToString(), options);    return View();} 

The preceding Code uses the RegisterPostEvictionCallback method to set the callback function. In this example, the callback function is called MyCallback. The second parameter is the status parameter you want to pass to the callback function, in this example, the HomeController instance is passed as a status parameter to the callback function.

The callback function is as follows:

private static void MyCallback(object key, object value, EvictionReason reason, object state){    var message = $"Cache entry was removed : {reason}";    ((HomeController)state).cache.Set("callbackMessage", message);}

Look at the code above. MyCallback () is a private static function in HomeController and has four parameters. The first two parameters are the key/value corresponding to the removed cached data. The third parameter indicates the reason for the removal. EvictionReason is an enumeration type, which may be caused by expiration, removal, or replacement.

In the function body, we define only one message of the string type to indicate the reason for removing the message. If we want to use this message as another cache item, we need to access the cache object of HomeController. In this case, we need to use the fourth parameter state. Use the state object to obtain the cache in HomeController, and Set a cache item named "callbackMessage" using the Set () method.

CallbackMessage can be obtained in Show () action:

public IActionResult Show(){    string timestamp = cache.Get<string>("timestamp");    ViewData["callbackMessage"] = cache.Get<string>("callbackMessage");    return View("Show", timestamp);}

On the Show page:

Test the callback method. Run the program and access the/Home/Index page. Then visit the/Home/Show page. Refresh the Show page until the cache expires. The page displays the cause of expiration.

9. cache priority

Like the expiration Policy, the cache priority is also MemoryCacheEntryOptions:

MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();options.Priority = CacheItemPriority.Normal;cache.Set<string>("timestamp", DateTime.Now.ToString(), options);

CacheItemPriority enumeration values are normal, high, and permanently retained.

10. Set the dependency between caches.

You can set dependencies for cache data to delete cache items that are dependent on them. Update Index () action according to the following code:

public IActionResult Index(){    var cts = new CancellationTokenSource();    cache.Set("cts", cts);    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();    options.AddExpirationToken(new CancellationChangeToken(cts.Token));    options.RegisterPostEvictionCallback(MyCallback, this);    cache.Set<string>("timestamp",DateTime.Now.ToString(), options);    cache.Set<string>("key1", "Hello World!",new CancellationChangeToken(cts.Token));    cache.Set<string>("key2", "Hello Universe!",new CancellationChangeToken(cts.Token));    return View();}
Note: Install the "Microsoft. Extensions. Primitives" package through NuGet and add references to System. Threading.

The above code first creates a CancellationTokenSource object and sets it to a cache item named "cts. Then create the MemoryCacheEntryOptions object and use the AddExpirationToken () method to specify a special expiration token (expiration token). Here we will not go into the CancellationChangeToken.

Expiration token allows you to "expire" a cache item. If the token is "active", the cache item is retained. If the token is "canceled", it is removed from the cache. Call the MyCallback method once the cache item is removed. The Code then creates two cache items key1 and key2. When the code is created, the third parameter passes a CancellationChangeToken initialized using the cts object.

Now we have three cache items. timestamp is the master cache item, key1 and key2 dependencies and timestamp. When the timestamp is removed, both key1 and key2 are removed. Remove the token from the timestamp.

public IActionResult Remove(){    CancellationTokenSource cts = cache.Get<CancellationTokenSource>("cts");    cts.Cancel();    return RedirectToAction("Show");}

We obtain the previously defined CancellationTokenSource object from the cache and execute the Cancel () method at the same time. The timestamp is removed and the key1 and key2 are also removed.

Test the above Code, run the program, access the/Home/Index page, and then access the/Home/Show page. At the same time, check whether the three cache items are displayed as expected. Access/Home/Remove and you will be directed to the/Home/Show page again. When the Remove () action is called, the token is marked as canceled and all values are removed. The Show page displays the Expiration Reason as "token expired ":

 

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.