.Net Core 跨平台開發實戰-服務器緩存:本地緩存、分佈式緩存、自定義緩存

.Net Core 跨平台開發實戰-服務器緩存:本地緩存、分佈式緩存、自定義緩存

1、概述

  系統性能優化的第一步就是使用緩存!什麼是緩存?緩存是一種效果,就是把數據結果存在某個介質中,下次直接重用。根據二八原則,80%的請求都集中在20%的數據上,緩存就是把20%的數據存起來,直接復用。Web系統緩存主要分為客戶端緩存、CDN緩存、反向代理緩存及服務器緩存,而服務器緩存又分類本地緩存、分佈式緩存。本節將給大家分享.Net Core 跨平台開發 服務器緩存開發實戰。

2、項目創建-ShiQuan.WebTest

  -》創建Asp.Net Core3.1 Web項目-shiquan.webtest,添加默認控制器-DefaultController 。

  開發環境使用VS2019 aps.net core 3.1  

  

   

  

  -》Action Index 方法

        public IActionResult Index()          {              /*Web 服務器響應請求時,設置緩存Cache-Control。單位為秒。*/              //base.HttpContext.Response.Headers[HeaderNames.CacheControl] = "public,max-age=600";//no-cache                base.ViewBag.Now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");              base.ViewBag.Url = $"{base.Request.Scheme}://{base.Request.Host}";//瀏覽器地址              base.ViewBag.InternalUrl = $"{base.Request.Scheme}://:{this._iConfiguration["port"]}";//應用程序地址              return View();          }

  -》在Startup 文件的Configure,使用UseStaticFile 指定當前路徑。

            //使用UseStaticFile 指定當前路徑              app.UseStaticFiles(new StaticFileOptions()              {                  FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot"))              });

  -》複製wwwroot 目錄及文件到debugbin 目錄。

   

  -》在Program文件中配置命令行獲取參數。

        public static void Main(string[] args)          {              //配置命令行獲取參數              new ConfigurationBuilder()                  .SetBasePath(Directory.GetCurrentDirectory())                  .AddCommandLine(args)//支持命令行參數                  .Build();                CreateHostBuilder(args).Build().Run();          }

  -》使用控制台,啟動Web項目-dotnet shiquan.webtest.dll –urls=http://*:5177 –port=5177。

   

  -》運行效果

  

3、本地緩存-MemoryCache

  下面我們來進行本地緩存-MemoryCache的開發,首先安裝MemoryCache安裝包

  

  -》Startup 配置添加MemoryCache的使用。

   

  -》本地緩存的調用

 

            var key = "defaultcontroller_info";              # region 服務器本地緩存-MemoryCache              {                  var time = string.Empty;                  if(this._iMemoryCache.TryGetValue(key,out time) == false)                  {                      time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");                      this._iMemoryCache.Set(key, time);                  }                  base.ViewBag.MemoryCacheNew = time;              }              #endregion

 

  -》Info 頁面內容

@{      ViewData["Title"] = "Home Page";  }        <div>          <h1>Index</h1>          <h2>瀏覽器地址:@base.ViewBag.Url</h2>          <h2>服務器地址:@base.ViewBag.InternalUrl</h2>          <h2>後台Action時間:@base.ViewBag.Now</h2>          <h2>MemoryCache時間:@base.ViewBag.MemoryCacheNew</h2>          <h2>RedisCache時間:@base.ViewBag.RedisCacheNow</h2>          <h2>CustomCache時間:@base.ViewBag.CustomCacheNow</h2>          <h2>前端View時間:@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")</h2>      </div>

 

  -》運行效果,後台Action及前端View時間,每次刷新都會更新,而內存緩存首次加載後,都將保存原有時間。

  

4、分佈式緩存-DistributedCache

  我們使用Redis作為分佈式緩存數據庫,首先下載安裝配置Redis數據庫,Redis數據庫默認端口:6379。

  

  -》在.Net core 項目中添加Microsoft.Extensions.Caching.Redis 安裝包

  

   -》在Startup文件中配置分佈式緩存

            /*增加分佈式緩存Redis*/              services.AddDistributedRedisCache(option => {                  option.Configuration = "127.0.0.1:6379";                  option.InstanceName = "DistributedRedisCache";              });

   -》控制器調用自定義緩存,實現內容保存與讀取,在頁面中顯示。

            #region 分佈式緩存-解決緩存在不同實例共享問題              {                  var time = this._iRedisCache.GetString(key);                  if (string.IsNullOrEmpty(time))                  {                      time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");                      this._iRedisCache.SetString(key, time, new DistributedCacheEntryOptions()                      {                          AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120) //過期時間                      });                  }                  base.ViewBag.RedisCacheNow = time;              }              #endregion

  -》運行效果,Redis 緩存在多個客戶端中也將不會改變。

 

5、自定義緩存-CustomCache

  我們來進行一次重複造輪子,實現類似內存緩存-MemoryCache的效果。首先我們定義自定義接口-ICustomCache,然後實現自定義緩存CustomCache。

using System;  using System.Collections.Generic;  using System.Linq;  using System.Threading.Tasks;    namespace ShiQuan.WebTest.Helpers  {      /// <summary>      /// 自定義緩存接口      /// </summary>      public interface ICustomCache      {          void Add(string key, object value);          T Get<T>(string key);          bool Exists(string key);          void Remove(string key);      }      /// <summary>      /// 自定義緩存      /// </summary>      public class CustomCache:ICustomCache      {          private readonly Dictionary<string, object> keyValues = new Dictionary<string, object>();          /// <summary>          /// 增加內容          /// </summary>          /// <param name="key"></param>          /// <param name="value"></param>          public void Add(string key,object value)          {              this.keyValues.Add(key, value);          }          /// <summary>          /// 獲取值          /// </summary>          /// <typeparam name="T"></typeparam>          /// <param name="key"></param>          /// <returns></returns>          public T Get<T> (string key)          {              return (T)this.keyValues[key];          }          /// <summary>          /// 判斷是否存在          /// </summary>          /// <param name="key"></param>          /// <returns></returns>          public bool Exists(string key)          {              return this.keyValues.ContainsKey(key);          }          /// <summary>          /// 移除值          /// </summary>          /// <param name="key"></param>          public void Remove(string key)          {              this.keyValues.Remove(key);          }      }  }

  -》項目註冊接口及實現

            /*增加自定義緩存*/              //services.AddTransient<ICustomCache, CustomCache>();//進程實例模式              services.AddSingleton<ICustomCache, CustomCache>(); //程序單例模式

  -》控制器調用自定義緩存,實現內容保存與讀取,在頁面中顯示。

            #region 自定義緩存              {                  var time = string.Empty;                  if (this._iCustomCache.Exists(key) == false)                  {                      time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");                      this._iCustomCache.Add(key, time);                  }                  time = this._iCustomCache.Get<String>(key);                  base.ViewBag.CustomCacheNow = time;              }              #endregion

 

  從運行的效果,我們可以看到,達到類似內存緩存MemoryCache的效果。

 

  至此,.net core 跨平台開發服務器緩存開發實戰介紹完畢,有不當地方,歡迎指正!