.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 目錄及檔案到debug\bin 目錄。
-》在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 跨平臺開發伺服器快取開發實戰介紹完畢,有不當地方,歡迎指正!