iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
自我挑戰組

.NET Core MVC網頁應用開發系列 第 27

.NET Core第27天_CacheTagHelper的使用

https://ithelp.ithome.com.tw/upload/images/20210927/20107452J23IGyZbAp.png

.net core mvc框架微軟有特別封裝緩存標籤協助程序(CacheTagHelper)。
CacheTagHelper:主要用於View中的資料緩存,原生HTML是沒有任何和cache有關的 tag的。

CacheTagHelper主要繼承自CacheTagHelperBase

using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Caching.Memory;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
    //
    // 摘要:
    //     Microsoft.AspNetCore.Razor.TagHelpers.TagHelper implementation targeting <cache>
    //     elements.
    public class CacheTagHelper : CacheTagHelperBase
    {
        //
        // 摘要:
        //     Prefix used by Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper instances when
        //     creating entries in Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper.MemoryCache.
        public static readonly string CacheKeyPrefix;

        //
        // 摘要:
        //     Creates a new Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper.
        //
        // 參數:
        //   factory:
        //     The factory containing the private Microsoft.Extensions.Caching.Memory.IMemoryCache
        //     instance used by the Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelper.
        //
        //   htmlEncoder:
        //     The System.Text.Encodings.Web.HtmlEncoder to use.
        public CacheTagHelper(CacheTagHelperMemoryCacheFactory factory, HtmlEncoder htmlEncoder);

        //
        // 摘要:
        //     Gets or sets the Microsoft.Extensions.Caching.Memory.CacheItemPriority policy
        //     for the cache entry.
        [HtmlAttributeName("priority")]
        public CacheItemPriority? Priority { get; set; }
        //
        // 摘要:
        //     Gets the Microsoft.Extensions.Caching.Memory.IMemoryCache instance used to cache
        //     entries.
        protected IMemoryCache MemoryCache { get; }

        [AsyncStateMachine(typeof(<ProcessAsync>d__11))]
        public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output);
    }
}

而CacheTagHelperBase繼承自TagHelper

using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Text.Encodings.Web;

namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
    //
    // 摘要:
    //     Microsoft.AspNetCore.Razor.TagHelpers.TagHelper base implementation for caching
    //     elements.
    public abstract class CacheTagHelperBase : TagHelper
    {
        //
        // 摘要:
        //     The default duration, from the time the cache entry was added, when it should
        //     be evicted. This default duration will only be used if no other expiration criteria
        //     is specified. The default expiration time is a sliding expiration of 30 seconds.
        public static readonly TimeSpan DefaultExpiration;

        //
        // 摘要:
        //     Creates a new Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelperBase.
        //
        // 參數:
        //   htmlEncoder:
        //     The Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelperBase.HtmlEncoder to use.
        public CacheTagHelperBase(HtmlEncoder htmlEncoder);

        public override int Order { get; }
        //
        // 摘要:
        //     Gets or sets the Microsoft.AspNetCore.Mvc.TagHelpers.CacheTagHelperBase.ViewContext
        //     for the current executing View.
        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }
        //
        // 摘要:
        //     Gets or sets a System.String to vary the cached result by.
        [HtmlAttributeName("vary-by")]
        public string VaryBy { get; set; }
        //
        // 摘要:
        //     Gets or sets a comma-delimited set of HTTP request headers to vary the cached
        //     result by.
        [HtmlAttributeName("vary-by-header")]
        public string VaryByHeader { get; set; }
        //
        // 摘要:
        //     Gets or sets a comma-delimited set of query parameters to vary the cached result
        //     by.
        [HtmlAttributeName("vary-by-query")]
        public string VaryByQuery { get; set; }
        //
        // 摘要:
        //     Gets or sets a comma-delimited set of route data parameters to vary the cached
        //     result by.
        [HtmlAttributeName("vary-by-route")]
        public string VaryByRoute { get; set; }
        //
        // 摘要:
        //     Gets or sets a comma-delimited set of cookie names to vary the cached result
        //     by.
        [HtmlAttributeName("vary-by-cookie")]
        public string VaryByCookie { get; set; }
        //
        // 摘要:
        //     Gets or sets a value that determines if the cached result is to be varied by
        //     the Identity for the logged in Microsoft.AspNetCore.Http.HttpContext.User.
        [HtmlAttributeName("vary-by-user")]
        public bool VaryByUser { get; set; }
        //
        // 摘要:
        //     Gets or sets a value that determines if the cached result is to be varied by
        //     request culture.
        //     Setting this to true would result in the result to be varied by System.Globalization.CultureInfo.CurrentCulture
        //     and System.Globalization.CultureInfo.CurrentUICulture.
        [HtmlAttributeName("vary-by-culture")]
        public bool VaryByCulture { get; set; }
        //
        // 摘要:
        //     Gets or sets the exact System.DateTimeOffset the cache entry should be evicted.
        [HtmlAttributeName("expires-on")]
        public DateTimeOffset? ExpiresOn { get; set; }
        //
        // 摘要:
        //     Gets or sets the duration, from the time the cache entry was added, when it should
        //     be evicted.
        [HtmlAttributeName("expires-after")]
        public TimeSpan? ExpiresAfter { get; set; }
        //
        // 摘要:
        //     Gets or sets the duration from last access that the cache entry should be evicted.
        [HtmlAttributeName("expires-sliding")]
        public TimeSpan? ExpiresSliding { get; set; }
        //
        // 摘要:
        //     Gets or sets the value which determines if the tag helper is enabled or not.
        [HtmlAttributeName("enabled")]
        public bool Enabled { get; set; }
        //
        // 摘要:
        //     Gets the System.Text.Encodings.Web.HtmlEncoder which encodes the content to be
        //     cached.
        protected HtmlEncoder HtmlEncoder { get; }
    }
}

他主要多一層繼承關係

新建CacheController.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Net5App6.Controllers
{
    public class CacheController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

跟相應的Index檢視

@{ 
    ViewData["Title"] = "CacheTahHelper Test";
}

<cache>
    @DateTime.Now
</cache>

當運行起來第一次時間跟之後再刷新都是第一次運行的緩存時間點,不會改變。
當再次刷新訪問會從緩存區將資料拿出藉此會發現效率較快,但資料筆叫不即時也可能不太適用需要即時資料更新呈現的網頁資料。
https://ithelp.ithome.com.tw/upload/images/20210927/20107452DRz9VuXBqP.png

enabled
<cache>預設有一個屬性叫enabled,默認情況為true代表要有緩存機至,而當有特別去設定為false時則會關閉此機制。(較少用)

expires-on
<cache>其實也是有時限的過一陣子(默認20分鐘)在訪問會有更新,那要很精確去設置更新緩存時間則可以用該屬性,可以用於設定絕對緩存到期日期。
要用DateTime設置絕對日期時間點(可到秒)

一個範例

@{ 
    ViewData["Title"] = "CacheTahHelper Test";
}

<cache>
    時間點(啟動緩存):@DateTime.Now
</cache>
<br>
<cache enabled="false">
    時間點(關閉緩存):@DateTime.Now
</cache>
<br>
<cache expires-on="@new DateTime(2021,8,4,17,5,30)">
    時間點(關閉緩存):@DateTime.Now
</cache>

預設第一個都無論怎麼重整都不變
第二個則是一直變
https://ithelp.ithome.com.tw/upload/images/20210927/20107452qHg4sRRuZE.png

當超過我們expires-on設置的時間後(超過到8/4下午5點5分30秒後)
可以看到第三個cache 資料也更新了

https://ithelp.ithome.com.tw/upload/images/20210927/20107452OgnbWhmIuh.png

expires-after
要用TimeSpan來設置時間區間,用於設定緩存時間長度。
通常會搭配TimeSpan跟FromMinutes()、FromSeconds()等方法設置By分鐘或秒為單位的緩存時長,比方指定過期時間長為30分鐘。

整併上述範本來比較

@{
    ViewData["Title"] = "CacheTahHelper Test";
}

<cache>
    時間點(啟動緩存):@DateTime.Now
</cache>
<br>
<cache enabled="false">
    時間點(關閉緩存):@DateTime.Now
</cache>
<br>
<cache expires-on="@new DateTime(2021,8,4,17,5,30)">
    時間點(直到特定時間才更新):@DateTime.Now
</cache>
<br>
<cache expires-after="@TimeSpan.FromSeconds(5)">
    時間點(過一段時間5秒才更新):@DateTime.Now
</cache>

expire-sliding
使用該屬性可以用於設置緩存資料未被存取訪問時該緩存資料要被逐出的時間。

@{
    ViewData["Title"] = "CacheTahHelper Test";
}

<cache expires-sliding="@TimeSpan.FromSeconds(5)">
    時間點(expires-sliding):@DateTime.Now
</cache>

比方這裡設置5秒則代表只要在沒超過5秒的期間就刷新,資料會一直保留。
當超過5秒間隔才刷新時緩存就會更新。

vary-by-header
使用該屬性接收逗號分隔的表頭值列表,於表頭有發生更改時候觸發緩存刷新。

vary-by-query
使用該屬性可接收URL上query string後方夾帶參數,以逗號分隔,當參數列表發生改變則更新緩存。
https://ithelp.ithome.com.tw/upload/images/20210927/20107452hFEJgffElk.png

vary-by-route
當路由參數發生改變時觸發緩存更新。
https://ithelp.ithome.com.tw/upload/images/20210927/2010745261MHmowjyN.png

本篇已同步發表至個人部落格
https://coolmandiary.blogspot.com/2021/08/net-core26cachetaghelper.html


上一篇
.NET Core第26天_ScriptTagHelper的使用
下一篇
.NET Core第28天_ValidationMessageTagHelper和ValidationSummaryTagHelper的使用
系列文
.NET Core MVC網頁應用開發30

尚未有邦友留言

立即登入留言