微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

文件缓存

缓存存储在文件中,根据过期时间过期,也可以手动删除。IIS回收进程时缓存不丢失。

代码

using System;
 System.Collections.Generic;
 System.IO;
 System.Linq;
 System.Security.Cryptography;
 System.Text;
 System.Threading.Tasks;
 System.Windows.Forms;
 System.Runtime.Serialization.Formatters.Binary;
 System.Threading;

namespace Common.Utils
{
    /// <summary>
    /// 缓存工具类
    </summary>
    public static class CacheUtil
    {
        #region 变量
        <summary>
         缓存路径
        </summary>
        private string folderPath = Application.StartupPath + "\\cache";
        object _lock = new object();
        static BinaryFormatter formatter = new BinaryFormatter();
        #endregion

        #region 构造函数
        static CacheUtil()
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
        }
        #region SetValue 保存键值对
         保存键值对
        void SetValue(string key,object value,1)">int expirationMinutes = 0)
        {
            CacheData data =  CacheData(key,value);
            data.updateTime = DateTime.@R_404_6363@;
            data.expirationMinutes = expirationMinutes;

            string keyMd5 = GetMD5(key);
            string path = folderPath + \\" + keyMd5 + .txt;
            lock (_lock)
            {
                using (FileStream fs =  FileStream(path,FileMode.OpenorCreate,FileAccess.Write))
                {
                    fs.SetLength();
                    formatter.Serialize(fs,data);
                    fs.Close();
                }
            }
        }
        #region GetValue 获取键值对
         获取键值对
        object GetValue(string key)
        {
            if (File.Exists(path))
            {
                 (CacheData)formatter.Deserialize(fs);
                    fs.Close();
                    if (data.expirationMinutes > 0 && DateTime.@R_404[email protected](data.updateTime).TotalMinutes > data.expirationMinutes)
                    {
                        File.Delete(path);
                        return null;
                    }
                    return data.value;
                }
            }
            ;
        }
        #region Delete 删除
         删除
        void Delete( (_lock)
                {
                    File.Delete(path);
                }
            }
        }
        #region Deleteall 全部删除
         全部删除
        void Deleteall()
        {
            string[] files = Directory.GetFiles(folderPath);
            foreach (string file in files)
            {
                File.Delete(file);
            }
        }
        #region 计算MD5值
         计算MD5值
        string GetMD5( value)
        {
            string base64 = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(value)).Replace(/",-);
            if (base64.Length > 200)
            {
                MD5CryptoServiceProvider md5 =  MD5CryptoServiceProvider();
                byte[] bArr = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value));
                StringBuilder sb =  StringBuilder();
                byte b  bArr)
                {
                    sb.Append(b.ToString(x2));
                }
                 sb.ToString();
            }
             base64;
        }
        #endregion
    }

    #region CacheData 缓存数据
     缓存数据
    </summary>
    [Serializable]
     CacheData
    {
        string key { get; set; }
        object value {  缓存更新时间
        public DateTime updateTime {  过期时间(分钟),0表示永不过期
        int expirationMinutes { ; }

        public CacheData(this.key = key;
            this.value = value;
        }
    }
    

}
View Code

文件依赖版:

 System.Threading;
 System.Web;

 缓存数据存储在文件void SetValue(HttpServerUtilityBase server,1)">string dependentFilePath,1)"> expirationMinutes;
            data.dependentFilePath = dependentFilePath;

            string folderPath = server.MapPath(~/bin/cacheDirectory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            object GetValue(HttpServerUtilityBase server,1)"> (CacheData)formatter.Deserialize(fs);
                    fs.Close();
                    FileInfo fileInfo =  FileInfo(data.dependentFilePath);
                    if (fileInfo.LastWriteTime > data.updateTime)
                    {
                        File.Delete(path);
                        void Delete(HttpServerUtilityBase server,1)">;
            File.Delete(path);
        }
         Deleteall(HttpServerUtilityBase server)
        {
             缓存依赖文件路径
        string dependentFilePath { 

}
View Code

文件依赖版使用示例:

 ProductController : Controller
{
    #region details页面
    public ActionResult details( name)
    {
        ViewBag.menu = product;

        string headKey = NetCMS.Web.Controllers.ProductController.details.head." + name;
        string bodyKey = NetCMS.Web.Controllers.ProductController.details.body.string dependentFilePath = Server.MapPath(~/Theme/pages/product/" + name + .html);

        List<string> fileList = Directory.GetFiles(Server.MapPath(~/") + Theme\\pages\\product).ToList();
        string file = fileList.Find(a =>
        {
            string fileName = Path.GetFileNameWithoutExtension(a);
            if (name == fileName)
            {
                true;
            }
            false;
        });

        string html = .Empty;
        if (CacheUtil.GetValue(Server,headKey) == null || CacheUtil.GetValue(Server,bodyKey) == )
        {
            using (StreamReader sr =  StreamReader(file))
            {
                html = sr.ReadToEnd();
                sr.Close();
            }
        }

        string body = string pre = \"" + Url.Content();
        body = ()CacheUtil.GetValue(Server,bodyKey);
        if (body == )
        {
            Regex reg = new Regex(@"<!--\s*头部结束\s*-->((?:[\s\S])*)<!--\s*公共底部\s*-->,RegexOptions.IgnoreCase);
            Match m = reg.Match(html);
             (m.Success)
            {
                body = m.Groups[1].Value;
            }
            else
            {
                body = .Empty;
            }

            body = body.Replace(\"js/Theme/js/);
            body = body.Replace(\"css/Theme/css/\"images/Theme/images/(images/(('images/('\"uploads/Theme/uploads/('uploads/);
            body = HtmlUtil.RemoveBlank(body);
            CacheUtil.SetValue(Server,bodyKey,body,dependentFilePath);
        }

        ViewBag.body = body;

        string head = .Empty;
        head = (if (head == )
        {
            Regex regHead = <head>((?:[\s\S])*)</head>noreCase);
            Match mHead = regHead.Match(html);
             (mHead.Success)
            {
                head = mHead.Groups[
            {
                head = .Empty;
            }

            head = head.Replace();
            head = head.Replace();
            CacheUtil.SetValue(Server,headKey,head,dependentFilePath);
        }

        ViewBag.head = head;

         View();
    }
    

}
View Code

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐