ASP.NET MVC Caching with OutputCache

本文介绍ASP.NET MVC中的缓存机制,包括缓存的基本概念、优势、何时使用及如何配置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");

        }

    }




内容概要:本文围绕EKF SLAM(扩展卡尔曼滤波同步定位与地图构建)的性能展开多项对比实验研究,重点分析在稀疏与稠密landmark环境下、预测与更新步骤同时进行与非同时进行的情况下的系统性能差异,并进一步探讨EKF SLAM在有色噪声干扰下的鲁棒性表现。实验考虑了不确定性因素的影响,旨在评估不同条件下算法的定位精度与地图构建质量,为实际应用中EKF SLAM的优化提供依据。文档还提及多智能体系统在遭受DoS攻击下的弹性控制研究,但核心内容聚焦于SLAM算法的性能测试与分析。; 适合人群:具备一定机器人学、状态估计或自动驾驶基础知识的科研人员及工程技术人员,尤其是从事SLAM算法研究或应用开发的硕士、博士研究生和相关领域研发人员。; 使用场景及目标:①用于比较EKF SLAM在不同landmark密度下的性能表现;②分析预测与更新机制同步与否对滤波器稳定性与精度的影响;③评估系统在有色噪声等非理想观测条件下的适应能力,提升实际部署中的可靠性。; 阅读建议:建议结合MATLAB仿真代码进行实验复现,重点关注状态协方差传播、观测更新频率与噪声模型设置等关键环节,深入理解EKF SLAM在复杂环境下的行为特性。稀疏 landmark 与稠密 landmark 下 EKF SLAM 性能对比实验,预测更新同时进行与非同时进行对比 EKF SLAM 性能对比实验,EKF SLAM 在有色噪声下性能实验
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值