.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


<<:  第 11 天 迈向下个阶段努力( leetcode 005 )

>>:  Unity与Photon的新手相遇旅途 | Day12-血量制作

[重构倒数第09天] - Vue-Cli + PurgeCSS 删除你用不到的CSS

前言 该系列是为了让看过Vue官方文件或学过Vue但是却不知道怎麽下手去重构现在有的网站而去规画的系...

Day28 资安小结 - 红队与蓝队 ( 内附名字由来 )

打了这麽多的技术文,突然发现我好像都没有介绍到资安的基础,所以最後的这 3 篇文章可能就是做个资安的...

尚气与十环传奇

尚气与十环传奇在线观看 漫威影业荣誉出品史诗冒险《尚气与十环传奇》,结合前所未见的震撼性动作、令人惊...

SEO网站优化技巧,为网站创建友好的图像,加快网站读取速度

你知道优化图像会增加你的网站的SEO排名吗?了解Web的图像优化如何提升网站速度有效提升在网站上的排...

集各领域专家修复的两大世界遗产

2019年世界上发生两个世界遗产的火灾,一个是法国巴黎的圣母院,一个是冲绳的首里城,两者建筑的修复难...