有些資料在資料庫中異動頻率極低, 但需要高頻率存取
這時候為了降低資料庫I/O可以將資料存在記憶體中
並設定可接受的回收時間, 確保資料正確性
不過如果是架設 Load Balance 就建議使用 Redis
NuGet: System.Runtime.Caching
using System; using System.Runtime.Caching; namespace Demo.Data.Service { public class DataService { public string Get() { var cKey = "Data"; ObjectCache _cache = MemoryCache.Default; string data; if (_cache.Get(cKey) == null) { data = "test123"; // 快取時間超過1分鐘後,回收快取 _cache.Set(cKey, data, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(1) }); } else { data = (string)_cache.Get(cKey); } if (data == null) return null; return data; } } }