深入学习ing

.Net(windows服务器)清理缓存数据的几个方法

  前言:最近在项目里将一批不常改变的数据做了缓存,但是一旦改变时需要立即更新缓存,针对此需求,开始接触清理缓存的研究,截止到目前,已经找到好几种方法了,供大家参考:

 

  1-(手动)使用IIS应用程序池,手动回收;

  2-(手动)如果应用程序池配置的:发生配置更改时禁止回收,的值是默认值False的话,可以通过修改应用配置文件:web.config;

  3-(自动)使用代码回收应用程序池,借助ServerManager管理类实现。参照下面代码示例;

  4-(自动、推荐)使用HttpRuntime.Cache缓存的机制清理,通过Cache.Remove清理指定缓存Key,也可以通过缓存依赖文件的机制通过修改缓存依赖文件来间接清理的办法;

 

其中前两种都是手动清理的方案,只能用于临时使用。   (核武器)

长久的办法还是推荐3和4,其中3属于整个应用的缓存全部回收了,这个一般情况下也不建议使用,除非整个项目更新可以。  (核武器)

方案4是重点推荐的方案,可以达到点对点清理或者清理依赖特定缓存文件的缓存数据。  (跟巡航导弹类似,指哪打哪)

 

方案三的代码如下,摘抄老师的源码:

/// <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
    }
View Code

 

方案四的代码如下,也是已拖老师的源码,自己做了帮助类封装特定的需求:

  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;
        }
    }
View Code

  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")
        {
        }
    }
View Code

 

  简单介绍一下封装类:将缓存类的使用做了抽象,每个子类对应一个对应的缓存文件用于清理特定业务的所有缓存,同时支持清理指定缓存。   

  缓存依赖项的机制推荐研究一下!!!

posted on 2020-11-19 10:43  深入学习ing  阅读(72)  评论(0编辑  收藏

导航

统计