ASP.NET MVC Caching with OutputCache

ASP.NET MVC Caching with OutputCache

[原文:http://tech.pro/tutorial/1434/aspnet-mvc-caching-with-outputcache]


We've all been to that site that just takes forever to load. It could be a slew of issues compounding to ultimately give you a bad user experience. A lot of websites today areread heavy; this means the site reads and serves content more than it creates content. These sites are prime for caching.

What is caching?

Let me step back first and explain what caching is. Wikipedia defines a cache as:

a cache is a component that transparently stores data so that future requests for that data can be served faster.

so caching means the act of storing data for future requests. This storage mechanism can include but not be limited to several forms: memory, disk, distributed cache engines, and databases.

What are the advantages to caching?

  • Incur expensive operations once.
  • Reduce server load during high peak times.
  • Faster load times.

Those all sound like great things to have for your application. Nothing is more stressful to me as a developer than a site going down due to heavy traffic. While caching is a silver bullet, it sure can help you in those sticky situations.

When should I cache?

  • When the content is universal
  • When the content is expensive
  • When the content will be visited multiple times within a session.
  • When staleness is not a concern.

Let me start off by addressing the idea of staleness. Everything in a system is stale, but there is a degree of staleness that we are willing to accept. Is that measured in seconds, minutes, hours, days or even years? You can cache according to all those time increments.

How do you cache with ASP.NET MVC ?

The best mechanism for caching in ASP.NET MVC would be to use the OutputCacheAttribute. The attribute decorates you actions and can be configured to cache based on different criteria: parameters, header values, encoding, and even custom criteria. So how does this attribute look like when decorating an action?

[OutputCache(Duration = 1000)]
public async Task<ActionResult> Index()
{
    using (Db)
    {
            var person = new Person { Name = "Khalid Abuhakmeh" };

        await Db.StoreAsync(person);
        await Db.SaveChangesAsync();

        return View(person);
    }
}


Notice I set the duration. Duration is set by seconds. In the example we are caching results of this action for 1000 seconds.

How to select a duration?

I personally like to cache for either really short periods (seconds) or really long periods (hours).

  • Short caches can handle traffic spikes while still giving the latest data. Your server can handle an obscene amount of requests if you even cache for 1 second. This is because only 1 request will be executed while subsequent (within that same second) requests will be served from cache. Your server can serve 1 request a second all day long.

  • Long caches can preserve server resources because the expensive operations will have only executed once per cache cycle. This is great for expensive reporting queries that are ranged for a specific day. There is no reason to run an expensive SQL statement more than once if the data is not changing.

When data changes, how do I react?

Inevitably users will feed your system new data and you have two options as to how to react.

  1. Let the cache expire naturally. It is not critical that the data get to the website instantly.

  2. Flush the OutputCache so that on the next request the newest data will be loaded. ASP.NET MVC has a method just for this.

Response.RemoveOutputCacheItem(Url.Action("index", "home"));


You can purge the cache by providing the url that points to the action that is cached. The code above should probably be called from your administrative side to flush your client side caches. It may also be called to flush screens that users have interacted with.

Conclusion

I covered the basics of caching, but it is a complex topic. Luckily the caching story in ASP.NET MVC is a really good one. Utilize it and understand how it can work for you. Also, I showed you how to purge your cache based on the url of the action. This is important for building responsive applications that have a lot of user interaction. Learning when to preserve your cache and when to purge it can give you the best of a dynamic application and a static application. Hope you find this post helpful and feel free to ask any questions.



=--=

http://hustlij.blog.163.com/blog/static/397601200992642348762/

一般使用方式:
1. 在Action上标记启用缓存,如:[OutputCache(Duration = 5, VaryByParam = 'none')]
2. 在Action上标记禁用本地缓存,如:[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
3. 在Action上标记使用缓存依赖,如:[OutputCache(Duration = 9999, VaryByParam = 'none', SqlDependency ='Demo:UserInfo')]
使用缓存依赖的要点
1.在Web.config中添加数据库连接字符串,如下:
<connectionStrings>
..<add name="DemoConn" connectionString="server=.\SQLEXPRESS;database=Demo;uid=sa;pwd=123456" providerName="System.Da ta.SqlClient"/>
</connectionStrings>
2.在Web.config中添加缓存配置,如下:
<caching>
..<sqlCacheDependency enabled="true" pollTime="2000">
....<databases>
......<add name="Demo" connectionStringName="DemoConn" />
....</databases>
..</sqlCacheDependency>
</caching>
3.在Global.asax.cs中以编程的方式启用缓存依赖,如下:
protected void Application_Start()
{
..string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DemoConn"].ConnectionString;
..System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connStr);
..System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, "UserInfo");
}
4.使用命令行注册依赖,如下:
aspnet_regsql -S .\sqlexpress -E -d DBName -ed

aspnet_regsql -S .\sqlexpress -E -d DBName -t TableName -et



示例如下:
    [HandleError]

    public class CacheHandlerController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }



        [OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]

        public ActionResult RenderWithOutCache()

        {

            ViewData["Now"] = DateTime.Now;

            return View("RenderCache");

        }



       [OutputCache(Duration = 5, VaryByParam = "none")]

        public ActionResult RenderCache()

        {

            ViewData["Now"] = DateTime.Now;

            return View();

        }



        [OutputCache(Duration = 9999, VaryByParam = "none", SqlDependency = "Demo:UserInfo")]

        public ActionResult SqlCacheDependency()

        {

            ViewData["Now"] = DateTime.Now;

            return View("RenderCache");

        }

    }




你可能感兴趣的:(asp.net,OutputCache)