我们经常会遇到这样的场景:
今天来了个业务,需要加一个字段,但是考虑的以后可能有变动,需要配成“活”的。
一般最初的做法就是加一个配置到Web.Config文件的AppSettings中去。但是这样有一个问题,那就是改一下配置节点,AppDomain就需要重启,很是不爽。
变通一点的会搞出一个xml文件,利用序列化去动态的读取。但是,哥!每次都读文件不觉得太耗IO吗?尤其是使用频率高话?

下面上代码吧,懒的废话了,关键地方都注释了,也不是什么高深的技术:

先来配置文件(注意Config路径要自己建,代码没有处理)和对应的配置文件代码:

<?xml version="1.0" encoding="utf-8"?>
<SimpleBizConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ID>12</ID>
<Key>MyKey</Key>
<ListSimple>
<string>简单</string>
<string>list</string>
<string>集合</string>
</ListSimple>
</SimpleBizConfig>
using System.Text;
using Glutton.Web.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace WebTest.Models
{
public class SimpleBizConfig : ISimpleConfig
{
/// <summary>
/// 默认配置文件路径
/// </summary>
public string GetPath()
{
return "~/Config/SimpleBizConfig.cfg";
} public string GetCacheKey()
{
return "~/MyConfig_SimpleBizConfig";
} public SimpleBizConfig()
{
this.ID = 1;
this.Key = "MyKey";
this.ListSimple = new List<string>();
} public int ID { get; set; } public string Key { get; set; } public List<string> ListSimple { get; set; } internal string Desc()
{
StringBuilder sb = new StringBuilder();
sb.Append("类型:SimpleBizConfig").Append("<br/>"); sb.Append("ID = " + this.ID.ToString()).Append("<br/>");
sb.Append("Key = " + this.Key).Append("<br/>"); sb.Append("list").Append("<br/>"); for (int i = 0; i < this.ListSimple.Count; i++)
{
sb.Append("index:" + i.ToString() + ",value:" + ListSimple[i]).Append("<br/>");
} return sb.ToString();
}
}
}

再来管理配置文件的类:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Xml.Serialization; namespace Glutton.Web.Configuration
{
public interface ISimpleConfig
{
string GetPath(); string GetCacheKey();
} public class ConfigManager
{
public static T GetConfig<T>() where T : class ,ISimpleConfig, new()
{
T tmpT = new T();
string cacheKey = tmpT.GetCacheKey(); //先尝试从cache中取数据
T t = GetFromCache<T>(cacheKey);//很郁闷,没有静态泛型接口 if (t != null)
{
return t;
} //cache没有数据,直接读配置文件
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); string configFilePath = HttpContext.Current.Server.MapPath(tmpT.GetPath()); if (!File.Exists(configFilePath))
{
//文件不存在,初始化,这里需要配置文件类实现默认的初始化动作
using (TextWriter writer = new StreamWriter(configFilePath))
{
t = new T();
xmlSerializer.Serialize(writer, t);
}
}
else
{
using (FileStream fs = new FileStream(configFilePath, FileMode.Open))
{
t = xmlSerializer.Deserialize(fs) as T;
}
} //存到缓存里面去,依赖web缓存的文件依赖功能实现监控配置文件修改
SetToCache<T>(cacheKey, configFilePath, t); return t;
} private static void SetToCache<T>(string cacheKey, string configFilePath, T t) where T : class ,new()
{
HttpRuntime.Cache.Insert(cacheKey, t, new CacheDependency(configFilePath), //文件依赖过期
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
} private static T GetFromCache<T>(string cacheKey) where T : class ,new()
{
return HttpRuntime.Cache[cacheKey] as T;
}
}
}

看看调用的方法,HomeController里面加了一个测试方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Glutton.Web.Configuration;
using WebTest.Models; namespace WebTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
} public ActionResult About()
{
ViewBag.Message = "Your application description page."; return View();
} public ActionResult Contact()
{
ViewBag.Message = "Your contact page."; return View();
} public string TestCfg()
{
return ConfigManager.GetConfig<SimpleBizConfig>().Desc();
}
}
}

看看效果,:-D:

利用XML序列化和Asp.Net Web缓存实现站点配置文件的更多相关文章

  1. JSON and XML Serialization in ASP.NET Web API

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-seri ...

  2. 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化

    谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...

  3. ASP.NET Web API路由系统:路由系统的几个核心类型

    虽然ASP.NET Web API框架采用与ASP.NET MVC框架类似的管道式设计,但是ASP.NET Web API管道的核心部分(定义在程序集System.Web.Http.dll中)已经移除 ...

  4. ASP.NET Web API框架揭秘:路由系统的几个核心类型

    ASP.NET Web API框架揭秘:路由系统的几个核心类型 虽然ASP.NET Web API框架采用与ASP.NET MVC框架类似的管道式设计,但是ASP.NET Web API管道的核心部分 ...

  5. Professional C# 6 and .NET Core 1.0 - Chapter 42 ASP.NET Web API

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处: -------------------------------------------------------- ...

  6. ASP.NET Web API中的JSON和XML序列化

    ASP.NET Web API中的JSON和XML序列化 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok ...

  7. Asp.Net Web API 2第十三课——ASP.NET Web API中的JSON和XML序列化

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...

  8. 在asp.net web api中利用过滤器设置输出缓存

    介绍 本文将介绍如何在asp.net web api中利用过滤器属性实现缓存. 实现过程 1,首先在web.config文件下appsettings下定义“CacheEnabled”和“CacheTi ...

  9. ASP.NET Web API编程——序列化与内容协商

    1 多媒体格式化器 多媒体类型又叫MIME类型,指示了数据的格式.在HTTP协议中多媒体类型描述了消息体的格式.一个多媒体类型包括两个字符串:类型和子类型. 例如: text/html.image/p ...

随机推荐

  1. MyBatis 学习总结(1)

    MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架,几乎消除了所有的 JDBC 代码和参数的手工设置以及结果集的处理,通过XML(sqlMapConfig)或注解配置数据源和 ...

  2. OpenCV创建轨迹条,图片像素的访问

    .OpenCV创建进度条以及图像对比度,亮度调整 1.创建轨迹条createTrackbar() 函数原型C++: intcreateTrackbar(conststring& trackba ...

  3. mongodb 查询数据

    MongoDB概念解析: 等同于SQL的数据库表:collectiondocument:等同于SQL的数据记录行field:等同于SQL的数据字段表连接,MongoDB不支持主键,MongoDB自动将 ...

  4. nodejs 操作文件系统读取写入文件

    我们通过fs这个模块来对文件系统进行操作,对于文件系统操作一般都有同步.异步方法,两者区别,同步等有返回结果时候,在继续执行后面的代码,异步是不等返回结果,直接执行后面的代码,待有返回结果时候,通过回 ...

  5. 使用Openssl编译svn并安装

    我的操作系统是CentOS 6.8.公司的svn服务器安装在windows系统中,并且使用 VisualSVN 对外提供https服务. 在centos 6.8上如果我使用yum 安装svn,那么根本 ...

  6. ASP.NET WebForm中JavaScript修改了页面上Label的值,如何在后台代码中获取

    在用ASP.NET WebForm开发一个项目时,遇到如下的一个情况 页面上有一个Textbox控件,还有2个Label 控件. 当Textbox控件中的值更改时,两个Label控件上的值做相应的更改 ...

  7. Ubuntu12.04安装svn1.8

    先在终端执行sudo sh -c 'echo "# WANdisco Open Source Repo" >> /etc/apt/sources.list.d/WANd ...

  8. 【hibernate-笔记】

    //1 创建,调用空参构造 Configuration conf = new Configuration().configure(); //2 根据配置信息,创建 SessionFactory对象 S ...

  9. C++基础之函数和作用域

    (1)函数的定义格式如下所示.<类型><函数名>(<形参表>) {<若干条语句>}其中,<类型>包含存储类和数据类型.存储类省略为外部函数, ...

  10. Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

    内容简介 本文主要说明在Java8及以上版本中,使用stream().filter()来过滤一个List对象,查找符合条件的对象集合. List对象类(StudentInfo) public clas ...