.NET Core第27天_CacheTagHelper的使用

 


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


CacheTagHelper主要繼承自CacheTagHelperBase

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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檢視

1
2
3
4
5
6
7
@{ 
    ViewData["Title"] = "CacheTahHelper Test";
}

<cache>
    @DateTime.Now
</cache>



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


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


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

一個範例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@{ 
    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>

預設第一個都無論怎麼重整都不變
第二個則是一直變

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






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

整併上述範本來比較

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@{
    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
使用該屬性可以用於設置緩存資料未被存取訪問時該緩存資料要被逐出的時間。

1
2
3
4
5
6
7
@{
    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後方夾帶參數,以逗號分隔,當參數列表發生改變則更新緩存。



vary-by-route
當路由參數發生改變時觸發緩存更新。




















留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header