在ASP.NET MVC 3缓存数据 [英] Caching Data in ASP.NET MVC 3

查看:129
本文介绍了在ASP.NET MVC 3缓存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 3应用程序,基本上只是一组Web服务。这些Web服务是由一组控制器动作暴露。每个控制器操作查询我的数据库。因为我的数据很少改变,而且,陈旧的数据是不是一个问题,我想我会实施一些cacheing来提高性能。我的目标是:

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. 从不缓存到用户的响应。

  2. 缓存数据库记录长达24小时。如果在24小时过后,再次命中数据库。

这是否有意义?我知道如何prevent从缓存中的响应。我只是用以下内容:

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

HttpContext.Response.Cache.SetCacheability(cacheability)

不过,我不知道如何缓存我的数据库记录在内存中长达24小时。有没有人对如何做到这一点有什么建议?我甚至不知道去哪里找。

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.

感谢您

推荐答案

您可以使用 System.Runtime.Caching 命名空间(或ASP.NET缓存,但这种是旧的,并且只能在web应用中使用)。

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).

下面是您可以使用环绕当前数据检索机制的样本函数。您可以更改参数MemoryCache.Add来控制它的多少缓存,但你要求的24小时以上。

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;
}

正如@Bond提到的,你也不妨来看看,如果你缓存的数据很可能会在24小时内更改使用SQL缓存依赖。如果它是pretty静态不过,这会做你的要求。

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.

这篇关于在ASP.NET MVC 3缓存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆