简体   繁体   中英

Caching Data in ASP.NET MVC 3

I have an ASP.NET MVC 3 app that is basically just a set of web services. These web services are exposed by a set of Controller actions. Each controller action queries my database. Because my data rarely changes, and, stale data is not a concern, I thought i would implement some cacheing to improve performance. My goals are:

  1. Never cache a response to a user.
  2. Cache the database records for up to 24 hours. If 24 hours has passed, hit the database again.

Does that make sense? I know how to prevent the response from caching. I just use the following:

HttpContext.Response.Cache.SetCacheability(cacheability)

However, I'm not sure how to cache my database records in memory for up to 24 hours. Does anyone have any suggestions on how to do this? I'm not even sure where to look.

Thank you

You can use the System.Runtime.Caching namespace (or the ASP.NET cache, but this is older and can only be used within web applications).

Here's a sample function which you can use to wrap around your current data retrieval mechanism. You can alter the parameters in MemoryCache.Add to control how much it's cached, but you requested 24h above.

using System.Runtime.Caching;    // At top of file

public IEnumerable<MyDataObject> GetData() 
{
    IEnumerable<MyDataObject> data = MemoryCache.Default.Get(MYCACHEKEY) as IEnumerable<MyDataObject>;
    if (data == null)
    {
        data = // actually get your data from the database here
        MemoryCache.Default.Add(MYCACHEKEY, data, DateTimeOffset.Now.AddHours(24));
    }
    return data;
}

As mentioned by @Bond, you may also wish to look at using an SQL Cache Dependency if the data you're caching is likely to change within the 24 hours. If it's pretty static though, this will do what you asked.

The MVC framework is persistence-agnostic. There are no built-in means to store data, so there are no built-in means to cache stored data.

The OutputCache attribute can be used to cache a server response. But you explicitly stated that that's not something you want to do.

However, you may still be able to use the built-in OutputCache if you want to stay within the MVC framework. Consider exposing the data you want to cache as a JSON result

[OutputCache(Duration = 86400)]
public JsonResult GetMyData() {
    var results = QueryResults();
    return Json(results);
}

The JSON string at /ControllerName/GetMyData will be cached for 24 hours, so the actual query will only be ran once per day. That means you'd have to implement an AJAX call on your final page, or make another HTTP call from your server. Neither of those are ideal.

I would look for another solution to your problem outside of the MVC framework. Consider memcached , which was created for exactly this purpose.

What you are talking about is not exactly MVC responsibility. ASP.Net allow you to cahce only the things it produces (and this they are responces, obviosly).

If you want to cache data it can be better to cachet it the same place it was produced - somewhere in BL or Data Layer.

You can do something like that:

public class DataCacher
{
    private static String data;
    private static DateTime updateTime;

    private DataCacher() { }

    public static String Data
    {
        get
        {
            if (data == null || updateTime > DateTime.Now)
            {
                data = "Insert method that requests your data form DB here: GetData()";
                updateTime = DateTime.Now.AddDays(1);
            }
            return data;
        }
    }
}

String data presents your actual data here. After adding this class replace your GetData() methods with DataCacher.Data .

Hope it helps or at least leads you to some further thinking.

If you're using MSSQL you may want to look at SQL Cache Dependency .

I'm not sure if you can configure cache expiration to 24 hours but with the cache dependency you may not need to - it will invalidate the cache as soon as there is an update on the database(ie should be more efficient than the time expiration strategy).

是一篇很好的文章,讨论了ASP.NET MVC 3的几个与性能相关的实践,并提到了缓存。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM