前言:最近在項目裏將一批不常改變的數據作了緩存,可是一旦改變時須要當即更新緩存,針對此需求,開始接觸清理緩存的研究,截止到目前,已經找到好幾種方法了,供你們參考:html
1-(手動)使用IIS應用程序池,手動回收;web
2-(手動)若是應用程序池配置的:發生配置更改時禁止回收,的值是默認值False的話,能夠經過修改應用配置文件:web.config;數據庫
3-(自動)使用代碼回收應用程序池,藉助ServerManager管理類實現。參照下面代碼示例;windows
4-(自動、推薦)使用HttpRuntime.Cache緩存的機制清理,經過Cache.Remove清理指定緩存Key,也能夠經過緩存依賴文件的機制經過修改緩存依賴文件來間接清理的辦法;數組
其中前兩種都是手動清理的方案,只能用於臨時使用。 (核武器)緩存
長久的辦法仍是推薦3和4,其中3屬於整個應用的緩存所有回收了,這個通常狀況下也不建議使用,除非整個項目更新能夠。 (核武器)app
方案4是重點推薦的方案,能夠達到點對點清理或者清理依賴特定緩存文件的緩存數據。 (跟巡航導彈相似,指哪打哪)ide
方案三的代碼以下,摘抄老師的源碼:工具
/// <summary> /// IIS應用程序池輔助類 /// </summary> public class IISManagerHelper { #region IIS 元數據庫和IIS 6配置兼容性 private const string HOST = "localhost"; /// <summary> /// 取得全部應用程序池 /// 要解決這個問題就得安裝「IIS 元數據庫和IIS 6配置兼容性」。 /// 「控制面板」->「程序和功能」->面板左側「打開或關閉windows功能」->「Internet信息服務」->「Web管理工具」->「IIS 6管理兼容性」->「IIS 元數據庫和IIS 6配置兼容性」。 /// </summary> /// <returns></returns> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static List<string> GetAppPools_IIS6() { DirectoryEntry appPools = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools", HOST)); return (from DirectoryEntry entry in appPools.Children select entry.Name).ToList(); } [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static PropertyCollection GetAppPoolProperties_IIS6(string appPoolName) { PropertyCollection propertyCollection = null; DirectoryEntry appPools = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools", HOST)); foreach (DirectoryEntry entry in appPools.Children) { if (entry.Name == appPoolName) { propertyCollection = entry.Properties; } } return propertyCollection; } /// <summary> /// 獲取應用程序數量 /// </summary> /// <param name="appName"></param> /// <returns></returns> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static int GetAppNumber_IIS6(string appName) { int appNumber; Hashtable hashTable = new Hashtable(); List<string> poolList = GetAppPools_IIS6(); //獲取應用程序池名稱數組 foreach (string i in poolList) //填充哈希表key值內容 { hashTable.Add(i, ""); } GetPoolWeb_IIS6(); Dictionary<string, int> dic = new Dictionary<string, int>(); foreach (string i in poolList) { appNumber = hashTable[i].ToString() != "" ? Convert.ToInt32(hashTable[i].ToString().Split(',').Length.ToString()) : 0; dic.Add(i, appNumber); } dic.TryGetValue(appName, out appNumber); return appNumber; } /// <summary> /// 獲取IIS版本 /// </summary> /// <returns></returns> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static string GetIisVersion_IIS6() { string version = string.Empty; try { DirectoryEntry getEntity = new DirectoryEntry("IIS://LOCALHOST/W3SVC/INFO"); version = getEntity.Properties["MajorIISVersionNumber"].Value.ToString(); } catch (Exception se) { //說明一點:IIS5.0中沒有(int)entry.Properties["MajorIISVersionNumber"].Value;屬性,將拋出異常 證實版本爲 5.0 } return version; } /// <summary> /// 判斷程序池是否存在 /// </summary> /// <param name="appPoolName">程序池名稱</param> /// <returns>true存在 false不存在</returns> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static bool IsAppPoolExsit_IIS6(string appPoolName) { bool result = false; DirectoryEntry appPools = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools", HOST)); foreach (DirectoryEntry entry in appPools.Children) { if (!entry.Name.Equals(appPoolName)) continue; result = true; break; } return result; } /// <summary> /// 建立應用程序池 /// </summary> /// <param name="appPool"></param> /// <returns></returns> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static bool CreateAppPool_IIS6(string appPool) { try { if (!IsAppPoolExsit_IIS6(appPool)) { DirectoryEntry appPools = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools", HOST)); DirectoryEntry entry = appPools.Children.Add(appPool, "IIsApplicationPool"); entry.CommitChanges(); return true; } } catch { return false; } return false; } /// <summary> /// 操做應用程序池 /// </summary> /// <param name="appPoolName"></param> /// <param name="method">Start==啓動 Recycle==回收 Stop==中止</param> /// <returns></returns> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static bool DoAppPool_IIS6(string appPoolName, string method) { bool result = false; try { DirectoryEntry appPools = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools", HOST)); DirectoryEntry findPool = appPools.Children.Find(appPoolName, "IIsApplicationPool"); findPool.Invoke(method, null); appPools.CommitChanges(); appPools.Close(); result = true; } catch (Exception) { result = false; } return result; } /// <summary> /// 刪除指定程序池 /// </summary> /// <param name="appPoolName">程序池名稱</param> /// <returns>true刪除成功 false刪除失敗</returns> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] public static bool DeleteAppPool_IIS6(string appPoolName) { bool result = false; DirectoryEntry appPools = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools", HOST)); foreach (DirectoryEntry entry in appPools.Children) { if (!entry.Name.Equals(appPoolName)) continue; try { entry.DeleteTree(); result = true; break; } catch { result = false; } } return result; } /// <summary> /// 得到全部的應用程序池和對應站點 /// </summary> [System.Obsolete("IIS 元數據庫和IIS 6配置兼容性")] private static void GetPoolWeb_IIS6() { Hashtable hashTable = new Hashtable(); List<string> poolList = GetAppPools_IIS6(); //獲取應用程序池名稱數組 foreach (string i in poolList) //填充哈希表key值內容 { hashTable.Add(i, ""); } DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC"); foreach (DirectoryEntry website in root.Children) { if (website.SchemaClassName != "IIsWebServer") continue; string comment = website.Properties["ServerComment"][0].ToString(); DirectoryEntry siteVDir = website.Children.Find("Root", "IISWebVirtualDir"); string poolname = siteVDir.Properties["AppPoolId"][0].ToString().Trim(); if (string.IsNullOrWhiteSpace(poolname)) { poolname = website.Properties["AppPoolId"][0].ToString().Trim(); } foreach (string i in poolList) { if (i != poolname) continue; if (hashTable[i].ToString() == "") hashTable[i] = comment; else hashTable[i] += "," + comment; } } root.Close(); } #endregion #region IIS7 /// <summary> /// 取得全部應用程序池 IIS7 /// https://forums.iis.net/t/1151611.aspx /// </summary> /// <returns></returns> public static List<ApplicationPool> GetAppPools() { return new ServerManager().ApplicationPools.ToList(); } /// <summary> /// 操做應用程序池 /// </summary> /// <param name="appPoolName"></param> /// <param name="method">Start==啓動 Recycle==回收 Stop==中止</param> /// <returns></returns> public static bool DoAppPool(string appPoolName, string method) { bool result = false; ServerManager iisManager = new ServerManager(); ApplicationPool appPool = iisManager.ApplicationPools[appPoolName]; if (appPool != null) { try { switch (method.ToLower()) { case "stop": appPool.Stop(); break; case "start": appPool.Start(); break; case "recycle": appPool.Recycle(); break; default: return false; } iisManager.CommitChanges(); result = true; } catch (Exception) { result = false; } } return result; } /// <summary> /// 建立應用程序池 /// https://wenku.baidu.com/view/6fc31eaad1f34693daef3e28.html /// </summary> /// <param name="appPoolName"></param> /// <param name="username"></param> /// <param name="pwd"></param> /// <returns></returns> public bool CreateAppPool(string appPoolName, string username, string pwd) { ServerManager iisManager = new ServerManager(); ApplicationPool appPool = iisManager.ApplicationPools.Add(appPoolName); appPool.AutoStart = true; appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated; appPool.ManagedRuntimeVersion = "v2.0"; appPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser; appPool.ProcessModel.UserName = username; appPool.ProcessModel.Password = pwd; iisManager.CommitChanges(); return true; } /// <summary> /// 編輯應用程序池 /// </summary> /// <param name="application"></param> /// <returns></returns> public static bool EditAppPool(ApplicationPool application) { string appPoolName = application.Name; ServerManager iisManager = new ServerManager(); ApplicationPool appPool = iisManager.ApplicationPools[appPoolName]; if (appPool != null) { appPool.ManagedRuntimeVersion = application.ManagedRuntimeVersion; appPool.ManagedPipelineMode = application.ManagedPipelineMode; iisManager.CommitChanges(); } return true; } /// <summary> /// 刪除指定程序池 /// </summary> /// <param name="appPoolName">程序池名稱</param> /// <returns>true刪除成功 false刪除失敗</returns> public static bool DeleteAppPool(string appPoolName) { ServerManager iisManager = new ServerManager(); ApplicationPool appPool = iisManager.ApplicationPools[appPoolName]; if (appPool != null) { iisManager.ApplicationPools.Remove(appPool); iisManager.CommitChanges(); } return true; } /// <summary> /// 判斷某一個站點是否存在 /// </summary> /// <param name="webSiteName"></param> /// <returns></returns> public bool IsExistWebSite(string webSiteName) { ServerManager iisManager = new ServerManager(); Site site = iisManager.Sites[webSiteName]; return site != null; } /// <summary> /// 建立某一個站點 /// </summary> /// <param name="webSiteName"></param> /// <param name="appPoolName"></param> /// <param name="schema"></param> /// <param name="port"></param> /// <param name="certHashString"></param> /// <param name="physicalPath"></param> public void CreateWebSite(string webSiteName, string appPoolName, string schema, int port, string certHashString, string physicalPath) { ServerManager iisManager = new ServerManager(); Site site = null; if (string.Compare(schema, "http", StringComparison.OrdinalIgnoreCase) == 0) { site = iisManager.Sites.Add(webSiteName, schema, string.Format("*:{0}:", port), physicalPath); } else if (string.Compare(schema, "https", StringComparison.OrdinalIgnoreCase) == 0) { byte[] certHashs = certHashString.HashStringToByteArray(); site = iisManager.Sites.Add(webSiteName, string.Format("*:{0}:", port), physicalPath, certHashs); //enable require SSL Configuration config = iisManager.GetApplicationHostConfiguration(); ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", webSiteName); accessSection["sslFlags"] = @"Ssl"; } else { throw new Exception();//ToDo….; } site.ServerAutoStart = true; site.Applications["/"].ApplicationPoolName = appPoolName; iisManager.CommitChanges(); } /// <summary> /// 刪除某一個站點 /// </summary> /// <param name="webSiteName"></param> public void DeleteWebSite(string webSiteName) { ServerManager iisManager = new ServerManager(); Site site = iisManager.Sites[webSiteName]; iisManager.Sites.Remove(site); iisManager.CommitChanges(); } #endregion }
方案四的代碼以下,也是已拖老師的源碼,本身作了幫助類封裝特定的需求:ui
a-老師的底層類:
/// <summary> /// 數據緩存總線(主要用在Web項目) /// </summary> [System.Diagnostics.DebuggerStepThrough] public partial class DataCacheBus { /// <summary> /// 判斷文件是否存在 /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static bool IsExistFilePath(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) return false; return File.Exists(filePath); } /// <summary> /// GenerateFile 將字符串寫成文件 /// </summary> private static void GenerateFile(string filePath, string fileContent) { string directoryPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { sw.Write(fileContent); sw.Flush(); } } } /// <summary> /// GenerateFile 生成文件 /// </summary> /// <param name="filePath"></param> public static void GenerateFile(string filePath) { if (!IsExistFilePath(filePath)) { GenerateFile(filePath, "author:wangyunpeng"); } } /// <summary> /// 插入緩存對象 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void Insert(string key, object value) { Insert(key, value, (CacheDependency)null); } /// <summary> /// 插入緩存對象(緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dependencyFile">文件依賴</param> public static void Insert(string key, object value, string dependencyFile) { GenerateFile(dependencyFile); Insert(key, value, new CacheDependency(dependencyFile)); } /// <summary> /// 插入緩存對象(緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dependencies">緩存依賴</param> public static void Insert(string key, object value, CacheDependency dependencies) { HttpRuntime.Cache.Insert(key, value, dependencies); } /// <summary> /// 插入緩存對象(緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dependencyFile">文件依賴</param> /// <param name="onRemoveCallBack">緩存消失以後的處理方法</param> public static void Insert(string key, object value, string dependencyFile, CacheItemRemovedCallback onRemoveCallBack) { GenerateFile(dependencyFile); HttpRuntime.Cache.Insert(key, value, new CacheDependency(dependencyFile), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 插入緩存對象(緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dependencies">緩存依賴</param> /// <param name="onRemoveCallBack">緩存消失以後的處理方法</param> public static void Insert(string key, object value, CacheDependency dependencies, CacheItemRemovedCallback onRemoveCallBack) { HttpRuntime.Cache.Insert(key, value, dependencies, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 插入緩存對象(絕對過時時間) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration">絕對過時時間</param> public static void Insert(string key, object value, DateTime absoluteExpiration) { Insert(key, value, absoluteExpiration, (CacheDependency)null); } /// <summary> /// 插入緩存對象(絕對過時時間) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration">絕對過時時間</param> /// <param name="dependencyFile">文件依賴</param> public static void Insert(string key, object value, DateTime absoluteExpiration, string dependencyFile) { GenerateFile(dependencyFile); HttpRuntime.Cache.Insert(key, value, new CacheDependency(dependencyFile), absoluteExpiration.ToUniversalTime(), Cache.NoSlidingExpiration); } /// <summary> /// 插入緩存對象(絕對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration">絕對過時時間</param> /// <param name="dependencies">緩存依賴</param> public static void Insert(string key, object value, DateTime absoluteExpiration, CacheDependency dependencies) { HttpRuntime.Cache.Insert(key, value, dependencies, absoluteExpiration.ToUniversalTime(), Cache.NoSlidingExpiration); } /// <summary> /// 插入緩存對象(絕對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration">絕對過時時間</param> /// <param name="dependencyFile">文件依賴</param> /// <param name="onRemoveCallBack">緩存消失以後的處理方法</param> public static void Insert(string key, object value, DateTime absoluteExpiration, string dependencyFile, CacheItemRemovedCallback onRemoveCallBack) { GenerateFile(dependencyFile); HttpRuntime.Cache.Insert(key, value, new CacheDependency(dependencyFile), absoluteExpiration.ToUniversalTime(), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 插入緩存對象(絕對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration">絕對過時時間</param> /// <param name="dependencies">緩存依賴</param> /// <param name="onRemoveCallBack">緩存消失以後的處理方法</param> public static void Insert(string key, object value, DateTime absoluteExpiration, CacheDependency dependencies, CacheItemRemovedCallback onRemoveCallBack) { HttpRuntime.Cache.Insert(key, value, dependencies, absoluteExpiration.ToUniversalTime(), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 插入緩存對象(相對過時時間) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="slidingExpiration">相對過時時間</param> public static void Insert(string key, object value, TimeSpan slidingExpiration) { Insert(key, value, slidingExpiration, (CacheDependency)null); } /// <summary> /// 插入緩存對象(相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="slidingExpiration">相對過時時間</param> /// <param name="dependencyFile">文件依賴</param> public static void Insert(string key, object value, TimeSpan slidingExpiration, string dependencyFile) { GenerateFile(dependencyFile); HttpRuntime.Cache.Insert(key, value, new CacheDependency(dependencyFile), Cache.NoAbsoluteExpiration, slidingExpiration); } /// <summary> /// 插入緩存對象(相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="slidingExpiration">相對過時時間</param> /// <param name="dependencies">緩存依賴</param> public static void Insert(string key, object value, TimeSpan slidingExpiration, CacheDependency dependencies) { HttpRuntime.Cache.Insert(key, value, dependencies, Cache.NoAbsoluteExpiration, slidingExpiration); } /// <summary> /// 插入緩存對象(相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="slidingExpiration">相對過時時間</param> /// <param name="dependencyFile">文件依賴</param> /// <param name="onRemoveCallBack">緩存消失以後的處理方法</param> public static void Insert(string key, object value, TimeSpan slidingExpiration, string dependencyFile, CacheItemRemovedCallback onRemoveCallBack) { GenerateFile(dependencyFile); HttpRuntime.Cache.Insert(key, value, new CacheDependency(dependencyFile), Cache.NoAbsoluteExpiration, slidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 插入緩存對象(相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="slidingExpiration">相對過時時間</param> /// <param name="dependencies">緩存依賴</param> /// <param name="onRemoveCallBack">緩存消失以後的處理方法</param> public static void Insert(string key, object value, TimeSpan slidingExpiration, CacheDependency dependencies, CacheItemRemovedCallback onRemoveCallBack) { HttpRuntime.Cache.Insert(key, value, dependencies, Cache.NoAbsoluteExpiration, slidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 插入緩存對象(絕對過時時間,相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration"></param> /// <param name="slidingExpiration"></param> /// <param name="dependencyFile"></param> public static void Insert(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, string dependencyFile) { GenerateFile(dependencyFile); HttpRuntime.Cache.Insert(key, value, new CacheDependency(dependencyFile), absoluteExpiration.ToUniversalTime(), slidingExpiration); } /// <summary> /// 插入緩存對象(絕對過時時間,相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration"></param> /// <param name="slidingExpiration"></param> /// <param name="dependencies"></param> public static void Insert(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheDependency dependencies) { HttpRuntime.Cache.Insert(key, value, dependencies, absoluteExpiration.ToUniversalTime(), slidingExpiration); } /// <summary> /// 插入緩存對象(絕對過時時間,相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration"></param> /// <param name="slidingExpiration"></param> /// <param name="dependencyFile"></param> /// <param name="onRemoveCallBack"></param> public static void Insert(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, string dependencyFile, CacheItemRemovedCallback onRemoveCallBack) { GenerateFile(dependencyFile); HttpRuntime.Cache.Insert(key, value, new CacheDependency(dependencyFile), absoluteExpiration.ToUniversalTime(), slidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 插入緩存對象(絕對過時時間,相對過時時間,緩存依賴) /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration"></param> /// <param name="slidingExpiration"></param> /// <param name="dependencies"></param> /// <param name="onRemoveCallBack"></param> public static void Insert(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheDependency dependencies, CacheItemRemovedCallback onRemoveCallBack) { HttpRuntime.Cache.Insert(key, value, dependencies, absoluteExpiration.ToUniversalTime(), slidingExpiration, CacheItemPriority.High, onRemoveCallBack); } /// <summary> /// 刪除緩存對象 /// </summary> /// <param name="key"></param> /// <returns>不等於null表示返回刪除的緩存對象,等於null表示緩存中沒有指定Key的緩存對象</returns> public static object Delete(string key) { return HttpRuntime.Cache.Remove(key); } /// <summary> /// 獲得緩存對象 /// </summary> /// <param name="key"></param> /// <returns>未找到該Key時爲 null</returns> public static object Get(string key) { return HttpRuntime.Cache.Get(key); } /// <summary> /// 獲取全部緩存信息(不包含已過時的緩存項) /// </summary> /// <returns></returns> public static IDictionaryEnumerator GetAll() { return HttpRuntime.Cache.GetEnumerator(); } /// <summary> /// 獲取知足查詢條件的Key的內容 /// </summary> /// <param name="keyContent">要查詢的key(能夠寫的不完整)</param> /// <param name="count">取出知足條件的最大數量</param> /// <returns></returns> public static List<string> GetKey(string keyContent = "_OLD_", bool contains = true, int count = 1000) { if (string.IsNullOrWhiteSpace(keyContent)) { throw new ArgumentException(nameof(keyContent)); } if (count < 1) { throw new ArgumentException(nameof(count)); } object @object = null; string key = null; keyContent = keyContent.ToLower(); List<string> list = new List<string>(count); IDictionaryEnumerator enumerator = GetAll(); while (enumerator.MoveNext()) { @object = enumerator.Key; if (@object is string) { key = (@object as string).ToLower(); if (contains) { if (key.Contains(keyContent)) { list.Add(key); } } else { if (!key.Contains(keyContent) && !key.EndsWith(".html")) { list.Add(key); } } if (list.Count == count) { break; } } } return list; } /// <summary> /// 獲取知足查詢條件的Key的數量 /// </summary> /// <param name="keyContent">要查詢的key(能夠寫的不完整)</param> /// <returns></returns> public static long GetKeyCount(string keyContent = "_OLD_", bool contains = true) { if (string.IsNullOrWhiteSpace(keyContent)) { throw new ArgumentException(nameof(keyContent)); } object @object = null; string key = null; long count = 0L; keyContent = keyContent.ToLower(); IDictionaryEnumerator enumerator = GetAll(); while (enumerator.MoveNext()) { @object = enumerator.Key; if (@object is string) { key = (@object as string).ToLower(); if (contains) { if (key.Contains(keyContent)) { System.Threading.Interlocked.Increment(ref count); } } else { if (!key.Contains(keyContent) && !key.EndsWith(".html")) { System.Threading.Interlocked.Increment(ref count); } } } } return count; } }
b-封裝幫助類-巡航導彈-推薦哈:
public abstract class PayBaseCache { /// <summary> /// 緩存文件依賴項 /// </summary> protected string DependencyFile { get; set; } public PayBaseCache(string dependencyFile) { this.DependencyFile = System.Web.Hosting.HostingEnvironment.MapPath("~/staticfiles/" + dependencyFile); DataCacheBus.GenerateFile(this.DependencyFile); } public void AddCache<T>(string cacheKey, T t, int cacheHours = 1) where T : class { if (DataCacheBus.Get(cacheKey) == null) { DataCacheBus.Insert(cacheKey, t, TimeSpan.FromHours(cacheHours), this.DependencyFile);//相對過時時間 } } public T GetCache<T>(string cacheKey) { T t = (T)DataCacheBus.Get(cacheKey);//相對過時時間 return t; } /// <summary> /// 刪除單個緩存 /// </summary> public void DeleteCache(string cacheKey) { DataCacheBus.Delete(cacheKey); } /// <summary> /// 刪除當前緩存類全部緩存數據 /// </summary> public void DeleteAllCache() { //這裏注意下:若是文件刪不了或者緩存沒有起到清除效果,有多是沒有文件權限 if (File.Exists(this.DependencyFile)) { File.Delete(this.DependencyFile); } } } /// <summary> /// 支付業務緩存 /// </summary> public class PayBIZCache : PayBaseCache { public static readonly PayBIZCache instance = new PayBIZCache(); public PayBIZCache() : base("payBizCache.html") { } } /// <summary> /// 支付業務緩存 /// </summary> public class PayAccountCache : PayBaseCache { public static readonly PayAccountCache instance = new PayAccountCache(); public PayAccountCache() : base("payAccountCache.html") { } }
簡單介紹一下封裝類:將緩存類的使用作了抽象,每一個子類對應一個對應的緩存文件用於清理特定業務的全部緩存,同時支持清理指定緩存。
緩存依賴項的機制推薦研究一下!!!