System.Web.Cache缓存的封装和调用示例

Posted zh672903

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了System.Web.Cache缓存的封装和调用示例相关的知识,希望对你有一定的参考价值。

HttpCache类

   /// <summary>
    /// System.Web.Cache缓存的封装
    /// </summary>
    public static class HttpCache
    
        /// <summary>
        /// 当前应用程序的的缓存实例
        /// </summary>
        public static System.Web.Caching.Cache Current
        
            get
            
                return HttpRuntime.Cache;
            
        

        /// <summary>
        /// 已缓存的缓存项数量
        /// </summary>
        public static int Count
        
            get
            
                return Current.Count;
            
        

        /// <summary>
        /// 获取某个缓存项
        /// </summary>
        /// <param name="key">键值</param>
        /// <returns></returns>
        public static object Get(string key)
        
            return Current.Get(key);
        

        /// <summary>
        /// 移除某个缓存项
        /// </summary>
        /// <param name="key">键值</param>
        /// <returns></returns>
        public static object Remove(string key)
        
            return Current.Remove(key);
        
        /// <summary>
        /// 清除所有缓存
        /// </summary>
        public static void Clear()
        
            var c = Current;
            foreach (DictionaryEntry v in c)
            
                c.Remove((string)v.Key);
            
        
        /// <summary>
        /// 添加缓存项
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="data">缓存数据</param>
        public static void Add(string key, object data)
        
            Current.Insert(key, data);
        
        /// <summary>
        /// 添加具有一个过期时间的缓存项
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="data">缓存数据</param>
        /// <param name="absoluteExpiration">绝对的过期时间,到此时间后缓存过期</param>
        public static void Add(string key, object data, DateTime absoluteExpiration)
        
            Current.Insert(key, data, null, absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
        
        /// <summary>
        /// 添加具有某些依赖项的缓存项
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="data">缓存数据</param>
        /// <param name="dependencies">依赖项</param>
        public static void Add(string key, object data, System.Web.Caching.CacheDependency dependencies)
        
            Current.Insert(key, data, dependencies);
        
        /// <summary>
        /// 添加与某些文件关连的缓存项,当这些文件被修改时缓存过期
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="data">缓存数据</param>
        /// <param name="files">缓存依赖的文件地址,当这些文件有变更时缓存项将自动失效</param>
        public static void Add(string key, object data, params string[] files)
        
            Current.Insert(key, data, new System.Web.Caching.CacheDependency(files));
        
        /// <summary>
        /// 添加具有一个过期时间并且与某些文件关连的缓存项,当过期时间已到或这些文件被修改时缓存过期
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="data">缓存数据</param>
        /// <param name="absoluteExpiration">绝对的过期时间,到此时间后缓存项自动过期</param>
        /// <param name="files">缓存依赖的文件地址,当这些文件有变更时缓存项将自动失效</param>
        public static void Add(string key, object data, DateTime absoluteExpiration, params string[] files)
        
            Current.Insert(key, data, new System.Web.Caching.CacheDependency(files), absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
        
        #region GetOrAdd
        /// <summary>
        /// 返回某个缓存项,如果不存在则调用函数委托获取值,并将值存入缓存后返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存项键值</param>
        /// <param name="handler">缓存项不存在时重新获取数据的函数委托</param>
        /// <returns></returns>
        public static T GetOrAdd<T>(string key, Func<T> handler)
        
            return (T)(Get(key).IfNull(() =>
            
                T v = handler.Invoke();
                if (v != null)
                
                    //存入缓存
                    Add(key, v);
                
                return v;
            ));
        
        /// <summary>
        /// 返回某个缓存项,如果不存在则调用函数委托获取值,并将值存入缓存后返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存项键值</param>
        /// <param name="absoluteExpiration">绝对的过期时间,当时间超过此值时缓存项将自动失效</param>
        /// <param name="handler">缓存项不存在时重新获取数据的函数委托</param>
        /// <returns></returns>
        public static T GetOrAdd<T>(string key, Func<T> handler, DateTime absoluteExpiration)
        
            return (T)(Get(key).IfNull(() =>
            
                T v = handler.Invoke();
                if (v != null)
                
                    //存入缓存
                    Add(key, v, absoluteExpiration);
                
                return v;
            ));
        
        /// <summary>
        /// 返回某个缓存项,如果不存在则调用函数委托获取值,并将值存入缓存后返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存项键值</param>
        /// <param name="dependencies">缓存依赖</param>
        /// <param name="handler">缓存项不存在时重新获取数据的函数委托</param>
        /// <returns></returns>
        public static T GetOrAdd<T>(string key, Func<T> handler, System.Web.Caching.CacheDependency dependencies)
        
            return (T)(Get(key).IfNull(() =>
            
                T v = handler.Invoke();
                if (v != null)
                
                    //存入缓存
                    Add(key, v, dependencies);
                
                return v;
            ));
        
        /// <summary>
        /// 返回某个缓存项,如果不存在则调用函数委托获取值,并将值存入缓存后返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存项键值</param>
        /// <param name="files">缓存依赖的文件地址,当这些文件有变更时缓存项将自动失效</param>
        /// <param name="handler">缓存项不存在时重新获取数据的函数委托</param>
        /// <returns></returns>
        public static T GetOrAdd<T>(string key, Func<T> handler, params string[] files)
        
            return (T)(Get(key).IfNull(() =>
            
                T v = handler.Invoke();
                if (v != null)
                
                    //存入缓存
                    Add(key, v, files);
                
                return v;
            ));
        
        /// <summary>
        /// 返回某个缓存项,如果不存在则调用函数委托获取值,并将值存入缓存后返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存项键值</param>
        /// <param name="absoluteExpiration">绝对的过期时间,当时间超过此值时缓存项将自动失效</param>
        /// <param name="files">缓存依赖的文件地址,当这些文件有变更时缓存项将自动失效</param>
        /// <param name="handler">缓存项不存在时重新获取数据的函数委托</param>
        /// <returns></returns>
        public static T GetOrAdd<T>(string key, Func<T> handler, DateTime absoluteExpiration, params string[] files)
        
            return (T)(Get(key).IfNull(() =>
            
                T v = handler.Invoke();
                if (v != null)
                
                    //存入缓存
                    Add(key, v, absoluteExpiration, files);
                
                return v;
            ));
        
        #endregion
    

Objects类

    /// <summary>
    /// 与Object相关的扩展函数
    /// </summary>
    public static class Objects
    
        #region 数据转换函数块
        /// <summary>
        /// 将某个对象转换为某种类型对象数据。
        /// 如果类型转换失败则返回对应目标类型的默认值,如果目标类型是枚举值,则返回第一个枚举值
        /// </summary>
        /// <typeparam name="T">需要转换的目标类型</typeparam>
        /// <param name="obj">需要转换的对象</param>
        /// <returns>转换后的类型数据</returns>
        /// <example>
        /// <code>
        /// int i = "1".As&lt;int&gt;();
        /// float f = "0.32".As&lt;float&gt;();
        /// DayOfWeek dayOfWeek = "Sunday".As&lt;DayOfWeek&gt;();
        /// DateTime time = "2011-01-01 23:00".As&lt;DateTime&gt;();
        /// </code>
        /// </example>
        public static T As<T>(this object obj)
        
            Type t = typeof(T);
            T replacement = default(T);
            if (t.IsEnum)
            
                //枚举类型。则获取第一个默认项
                replacement = (T)Enum.GetValues(t).GetValue(0);
            
            //else if (t == typeof(string))
            //
            //    //字符串,则以空字符串为默认值
            //    //replacement = (T)(object)string.Empty;
            //
            return As<T>(obj, replacement);
        
        /// <summary>
        /// 将某个对象转换为某种类型对象数据。 如果类型转换失败则返回替换值
        /// </summary>
        /// <typeparam name="T">需要转换的目标类型</typeparam>
        /// <param name="obj">对象</param>
        /// <param name="replacement">如果转换失败则返回此替换值</param>
        /// <returns>转换后的类型数据, 如果类型转换失败则返回<paramref name="replacement"/>表示的替换值</returns>
        /// <example>
        /// <code>
        /// object v = null;
        /// int i = v.As&lt;int&gt;(0);                     //i = 0;
        /// float f = "0.32".As&lt;float&gt;(0);            //f = 0.32;
        /// string s = v.As&lt;string&gt;("null");          //s = "null";
        /// DateTime time = v.As&lt;DateTime&gt;(DateTime.Now); //time = DateTime.Now;
        /// </code>
        /// </example>
        public static T As<T>(this object obj, T replacement)
        
            return (T)obj.As(typeof(T), replacement);
        

        /// <summary>
        /// 转换为某种类型
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="targetType">目标类型</param>
        /// <param name="replacement">如果转换失败则返回此替换值</param>
        /// <returns></returns>
        public static object As(this object obj, Type targetType, object replacement)
        
            if (obj == null) return replacement;

            TypeCode targetTC = Type.GetTypeCode(targetType);
            Type sourceType = obj.GetType();

            if (!targetType.IsInstanceOfType(obj))
            
                if (sourceType.IsEnum)
                
                    //枚举类型,则特殊对待
                    try
                    
                        return Convert.ChangeType(obj, targetType);
                    
                    catch
                    
                        return replacement;
                    
                
                else
                
                    switch (targetTC)
                    
                        case TypeCode.Empty:
                            return null;
                        case TypeCode.Object:
                            return replacement;
                        case TypeCode.DBNull:
                            return DBNull.Value;
                        case TypeCode.String:
                            return obj.ToString();
                        default:
                            bool error;
                            var v = obj.ToString().ConvertTo(targetType, out error);
                            return error ? replacement : v;
                    
                
            
            else
            
                return obj;
            
        

        /// <summary>
        /// 将某个对象转换为字符串对象
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="empty">如果对象为null则返回此字符</param>
        /// <returns>对象的字符串表示方式。如果对象为null则返回<paramref name="empty"/>表示的字符串</returns>
        public static string ToString(this object obj, string empty)
        
            if (obj == null) return empty;
            return obj.ToString();
        
        /// <summary>
        /// 将某个对象转换为Json字符数据
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>对象的Json格式的字符串。
        /// 对于DateTime类型的数据则返回“\/Date(时间戳)\/”的字符串数据;
        /// 而对于字符串,则对于非英文字母、数字的字符则返回utf码表示的字符。如对于中文的“我”则返回“\u6211”</returns>
        public static string ToJson(this object obj)
        
            if (obj == null) return "null";
            TypeCode code = Convert.GetTypeCode(obj);
            switch (code)
            
                case TypeCode.Boolean:
                    return ((bool)obj) ? "true" : "false";
                case TypeCode.DateTime:
                    DateTime d = (DateTime)obj;
                    return string.Format("\"\\/Date(0)\\/\"", d.ToTimestamp());
                case TypeCode.Empty:
                case TypeCode.DBNull:
                    return "null";
                case TypeCode.String:
                case TypeCode.Char:
                    return string.Format("\"0\"", obj.ToString().TojavascriptString());
                case TypeCode.Object:
                    return ObjectToJson(obj);
                default:
                    return obj.ToString();
            
        

        /// <summary>
        /// 将某个对象转换为Json数据
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static string ObjectToJson(object obj)
        
            //处理数组的情况
            if (obj is IEnumerable) return ListObjectToJson((IEnumerable)obj);

            StringBuilder buffer = new StringBuilder(64);
            buffer.Append("");
                        

            //取得公共属性
            PropertyDescriptorCollection pros = TypeDescriptor.GetProperties(obj);
            foreach (PropertyDescriptor p in pros)
            
                if (buffer.Length != 1) buffer.Append(",");
                buffer.AppendFormat("\"0\":1", p.Name.ToJavaScriptString(), p.GetValue(obj).ToJson());
            

            //取得公共字段
            Type type = obj.GetType();
            foreach (FieldInfo f in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
            
                if (buffer.Length != 1) buffer.Append(",");
                buffer.AppendFormat("\"0\":1", f.Name.ToJavaScriptString(), f.GetValue(obj).ToJson());
            

            buffer.Append("");

            return buffer.ToString();
        
        /// <summary>
        /// 将集合、列表对象转换为Json数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private static string ListObjectToJson(IEnumerable list)
        
            StringBuilder buffer = new StringBuilder(64);
            buffer.Append("[");
            foreach (object v in list)
            
                if (buffer.Length != 1) buffer.Append(",");
                buffer.Append(v.ToJson());
            
            buffer.Append("]");
            return buffer.ToString();
        
        #endregion

        /// <summary>
        /// 如果对象为null则调用函数委托并返回函数委托的返回值。否则返回对象本身
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="func">对象为null时用于调用的函数委托</param>
        /// <returns>如果对象不为null则返回对象本身,否则返回<paramref name="func"/>函数委托的返回值</returns>
        /// <example>
        /// <code>
        /// string v = null;
        /// string d = v.IfNull&lt;string&gt;(()=>"v is null");  //d = "v is null";
        /// string t = d.IfNull(() => "d is null");              //t = "v is null";
        /// </code>
        /// </example>
        public static T IfNull<T>(this T obj, Func<T> func)
            where T : class
        
            if (obj == null)
            
                return func == null ? default(T) : func();
            
            else
            
                return obj;
            
        
    

调用示例

  • 文件依赖缓存调用示例
       private static void TestHttpCache()
        

            string filePath = @"D:\report_data2.txt";
            while (true)
            
                Thread.Sleep(1000);

                Func<string> func = () =>  return testInsertCache(); ;
                HttpCache.GetOrAdd<string>("testHttpCache", func, new CacheDependency(filePath));
                string cacheStr = (string)HttpCache.Get("testHttpCache");
                Console.WriteLine(cacheStr);
            
        


        private static string testInsertCache()
        
            string line=string.Empty;
            try
            
                string filePath = @"D:\report_data2.txt";
                // 创建一个 StreamReader 的实例来读取文件 ,using 语句也能关闭 StreamReader
                using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
                
                    line = sr.ReadToEnd();
                
            
            catch (Exception e)
            
                // 向用户显示出错消息
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            
            return line;
        

可以明显的看到,当修改"D:\report_data2.txt"文件内容并保存的时候,缓存内容会自己进行更新。

以上是关于System.Web.Cache缓存的封装和调用示例的主要内容,如果未能解决你的问题,请参考以下文章

封装异步API

经典研析搜索引擎缓存技术中版权默示许可制度的突破

在 Electron 应用程序中缓存 API 调用的结果

第三方接口调用封装

iOS数据库离线缓存思路和网络层封装

iOS数据库离线缓存思路和网络层封装