首页 > 其他 > 详细

文件缓存

时间:2016-12-29 23:24:45      阅读:197      评论:0      收藏:0      [点我收藏+]

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

代码:

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

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

        #region 构造函数
        static CacheUtil()
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
        }
        #endregion

        #region SetValue 保存键值对
        /// <summary>
        /// 保存键值对
        /// </summary>
        public static void SetValue(string key, object value, int expirationMinutes = 0)
        {
            CacheData data = new CacheData(key, value);
            data.updateTime = DateTime.Now;
            data.expirationMinutes = expirationMinutes;

            string keyMd5 = GetMD5(key);
            string path = folderPath + "\\" + keyMd5 + ".txt";
            lock (_lock)
            {
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    fs.SetLength(0);
                    formatter.Serialize(fs, data);
                    fs.Close();
                }
            }
        }
        #endregion

        #region GetValue 获取键值对
        /// <summary>
        /// 获取键值对
        /// </summary>
        public static object GetValue(string key)
        {
            string keyMd5 = GetMD5(key);
            string path = folderPath + "\\" + keyMd5 + ".txt";
            if (File.Exists(path))
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    CacheData data = (CacheData)formatter.Deserialize(fs);
                    fs.Close();
                    if (data.expirationMinutes > 0 && DateTime.Now.Subtract(data.updateTime).TotalMinutes > data.expirationMinutes)
                    {
                        File.Delete(path);
                        return null;
                    }
                    return data.value;
                }
            }
            return null;
        }
        #endregion

        #region Delete 删除
        /// <summary>
        /// 删除
        /// </summary>
        public static void Delete(string key)
        {
            string keyMd5 = GetMD5(key);
            string path = folderPath + "\\" + keyMd5 + ".txt";
            if (File.Exists(path))
            {
                lock (_lock)
                {
                    File.Delete(path);
                }
            }
        }
        #endregion

        #region DeleteAll 全部删除
        /// <summary>
        /// 全部删除
        /// </summary>
        public static void DeleteAll()
        {
            string[] files = Directory.GetFiles(folderPath);
            foreach (string file in files)
            {
                File.Delete(file);
            }
        }
        #endregion

        #region 计算MD5值
        /// <summary>
        /// 计算MD5值
        /// </summary>
        private static string GetMD5(string value)
        {
            string base64 = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(value)).Replace("/", "-");
            if (base64.Length > 200)
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                byte[] bArr = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value));
                StringBuilder sb = new StringBuilder();
                foreach (byte b in bArr)
                {
                    sb.Append(b.ToString("x2"));
                }
                return sb.ToString();
            }
            return base64;
        }
        #endregion
    }

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

        public CacheData(string key, object value)
        {
            this.key = key;
            this.value = value;
        }
    }
    #endregion

}
View Code

 

文件缓存

原文:http://www.cnblogs.com/s0611163/p/6234960.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!