日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET MVC Caching with OutputCache

發布時間:2023/12/15 asp.net 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.

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

  • 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.Data.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 MVC Caching with OutputCache的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。