asp.net 缓存依赖demo

 示例简述:

项目中使用的城市数据、分类数据、站点数据、项目数据等少量且不怎么会变动的数据,不愿意存在数据库。

这个时候可以考虑放在一个文件中,xml或者txt都可以,然后将数据缓存到内存,加上缓存依赖,数据文件修改

后缓存自动失效,程序访问时,可以重新访问文件加载最新数据,并再次保存到内存中。

 

City.xml

复制代码
<?xml version="1.0" encoding="utf-8" ?>
<Citys>
  <city>
    <code>A01</code>
    <name>北京</name>
  </city>
  <city>
    <code>A02</code>
    <name>上海</name>
  </city>
  <city>
    <code>A03</code>
    <name>广州</name>
  </city>
  <city>
    <code>A04</code>
    <name>深圳3</name>
  </city>
</Citys>
复制代码

 

缓存帮助类

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CacheDependency
{
    public class MeCache
    {
        /// <summary>
        /// 设置以缓存依赖的方式缓存数据
        /// </summary>
        /// <param name="cacheKey">索引键值</param>
        /// <param name="objObject">缓存对象</param>
        /// <param name="dep"></param>
        public static void SetCache(string cacheKey, object objObject, System.Web.Caching.CacheDependency caDep)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(
                cacheKey,
                objObject,
                caDep,
                System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
                System.Web.Caching.Cache.NoSlidingExpiration, //禁用可调过期
                System.Web.Caching.CacheItemPriority.Default,
                null);
        }



        /// <summary>
        /// 获取当前应用程序指定CacheKey的Cache对象值
        /// </summary>
        /// <param name="cacheKey">索引键值</param>
        /// <returns>返回缓存对象</returns>
        public static object GetCache(string cacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[cacheKey];
        }

    }
}
复制代码

 

城市数据读取类

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace CacheDependency
{
    public class CityData
    {
        static CityData()
        {
            InitCity();
        }

        private static List<CityModel> InitCity()
        {
            List<CityModel> listCity = ReadCityXml();
            string path = System.AppDomain.CurrentDomain.BaseDirectory + "" + "City.xml";
            System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(path);
            MeCache.SetCache("city", listCity, dep);

            return listCity;
        }


        public static List<CityModel> GetCity()
        {
            object obj = MeCache.GetCache("city");
            if (obj == null)
            {
                return InitCity();

            }
            else
            {
                return (List<CityModel>)obj;
            }

        }




        public static List<CityModel> ReadCityXml()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            string path = System.AppDomain.CurrentDomain.BaseDirectory + "" + "City.xml";
            doc.Load(path);

            System.Xml.XmlNodeList list = doc.SelectNodes("//city");

            List<CityModel> listCity = new List<CityModel>();
            foreach (XmlNode item in list)
            {
                XmlNode t = item.SelectSingleNode("code");
                XmlNode t2 = item.SelectSingleNode("name");

                CityModel model = new CityModel();
                model.Code = t.InnerText;
                model.Name = t2.InnerText;

                listCity.Add(model);
            }
            return listCity;
        }
    }

    public class CityModel
    {
        public string Code { get; set; }

        public string Name { get; set; }
    }
}
复制代码

 

测试代码:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CacheDependency
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
            List<CityModel> list = CityData.GetCity();
            if (list != null)
            {
                foreach (var item in list)
                {
                    Response.Write(item.Code + "----" + item.Name);
                    Response.Write("<br/>");
                }
            }

            Response.Write("<br/>");
            Response.Write("ok!");
        }
    }
}
复制代码

 

 

以上代码是一个完整的缓存依赖数据示例。

不过少了一个地方,缓存失效后,重新读取,并加入缓存的地方,没有加lock可能存在并发问题;

 加限制参考单例双重验证模式。

 

posted on   荆棘人  阅读(187)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示