iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 19
2
Modern Web

輕量高效.NET Core開源Blog引擎:Miniblog.Core系列 第 19

19.研究OutputCache、ResponseCache兩快取差異

使用快取可以有效幫忙節省重複行為的性能。
asp.net core最常用快取[ResponseCache]跟asp.net [OutputCache]不一樣,多出先決很多條件。

所以madskristensen大有做一個專案:WebEssentials.AspNetCore.OutputCaching可以沿用在asp.net的習慣和兼具asp net core的特點,接著研究兩者的差異。

差異點

主要差異在asp.net OutputCache使用原理是使用Cache-Control Http Header對瀏覽器說明需要快取並緩存。

cache-control →public, max-age=存活時間

但在asp.net core使用ResponseCache不只屬於客戶端緩存,也使用服務器端緩存,所以兩者的定位是不一樣的。

舉例
前者在使用者瀏覽器清理瀏覽器暫存,快取也隨之被清除;而後者就算瀏覽器被清除,還是有伺服器記憶體快取存在,不需要再去讀取一次Action內容。

從Asp.NET OutputCache 比較開始

Asp.NET MVC沒有OutputCache版本,Header-Cache-Control預設是private

public ActionResult Index()
{
    return View();
}

2018-10-20.00.45.02-image.png

Asp.NET MVC有OutputCache版本,Header-Cache-Control預設值為public並且指定存活時間。

[OutputCache(Duration = 60)]
public ActionResult Index()
{
    return View();
}		

2018-10-20.00.53.48-image.png

Asp.NET Core ResponseCache 比較

Asp.NET Core MVC沒有OutputCache版本,Header-Cache-Control預設存活時間為0
2018-10-20.01.12.02-image.png

Asp.NET Core MVC有OutputCache版本,Header-Cache-Control預設值為public
2018-10-20.01.16.05-image.png

Asp.NET Core ResponseCache簡單使用方式

在Startup類別ConfigureServices使用AddResponseCaching方法註冊;在Configure使用UseResponseCaching使用Cache功能。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCaching();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseResponseCaching();
    }
}

接著在Action添加ResponseCache annotation

[ResponseCache(Duration = 300, VaryByQueryKeys = new string[] { "自訂Key值" })]
public IActionResult Index()
{
    return View();
}

WebEssentials.AspNetCore.OutputCaching使用方式:

在Startup類別ConfigureServices方法使用AddOutputCaching註冊。
這邊注意需要新建一個OutputCacheProfile物件添加到Profiles["自訂option KEY值"]

public class Startup{
	public void ConfigureServices(IServiceCollection services){
        services.AddOutputCaching(options =>
        {
            options.Profiles["自訂option KEY值"] = new OutputCacheProfile
            {
                Duration = 3600
            };
        });	
	}
}

接著在ActionResult添加annotation [OutputCache(自訂option KEY值)]使用快取功能。

[OutputCache(Profile = "自訂option KEY值")]
public IActionResult Index()
{
    return View();
}

參考


上一篇
18.IT鐵人賽文章同步更新Miniblog文章
下一篇
20.研究PWA漸進式增強Web APP(上) : 建立、使用方式
系列文
輕量高效.NET Core開源Blog引擎:Miniblog.Core30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言