ASP.NET下使用xml反序列化、缓存依赖实现个性化配置文件的实时生效
程序员文章站
2022-07-04 20:40:16
因为一些配置属性比较多,存在多组属性,因此结合xml解析、缓存技术,实现配置文化的自动解析、存入缓存、缓存依赖实时更新配置内容。
配置文件反序列化存入缓存的核心方法:...
因为一些配置属性比较多,存在多组属性,因此结合xml解析、缓存技术,实现配置文化的自动解析、存入缓存、缓存依赖实时更新配置内容。
配置文件反序列化存入缓存的核心方法:
public class.settings getsettings() { if (httpruntime.cache["settings"] != null) return (class.settings)httpruntime.cache["settings"]; string rootpath = getpath(); #region rootpath if (rootpath == "") { log.write(msgtype.fatal, "配置文件根目录rootpath为空"); return null; } else { if (!rootpath.endswith("\\")) rootpath += "\\"; rootpath = rootpath + "settings\\settings.config"; } #endregion if (!file.exists(rootpath)) { log.write(msgtype.fatal, "配置文件根目录rootpath为空"); return null; } string content = file.readalltext(rootpath, encoding.default); class.settings model = publicmethod.xmlserialize.deserializexml<class.settings>(content); log.write(msgtype.information, "读取配置文件"); cachedependency cd = new cachedependency(rootpath); httpruntime.cache.add("settings", model, cd, datetime.now.addminutes(5), timespan.zero, cacheitempriority.high, null); return model; }
上面自动获取rootpath的方法:
/// <summary> /// 取当前根目录的方法 /// </summary> private static string getpath() { string rootpath = ""; system.diagnostics.process p = system.diagnostics.process.getcurrentprocess(); //webdev.webserver visual studio web server //xxx.vhost winform //w3wp iis7 //aspnet_wp iis6 //iisexpress vs2013 string processname = p.processname.tolower(); if (processname == "aspnet_wp" || processname == "w3wp" || processname == "webdev.webserver" || processname == "iisexpress") { if (system.web.httpcontext.current != null) rootpath = system.web.httpcontext.current.server.mappath("~/"); else //当控件在定时器的触发程序中使用时就为空 { rootpath = system.appdomain.currentdomain.basedirectory; } } return rootpath; }
settings实体类的定义,要注意,这里的实体类要和settings配置文件对应,否则反序列化会出错:
[xmlroot(namespace = "", isnullable = false, elementname = "settings")] public class settings { #region 属性 [xmlelement("logger")] public loggerconfig logger { get; set; } #endregion #region 子类 [xmltype(typename = "logger")] public class loggerconfig { public string loglevel { get; set; } public string savepath { get; set; } } #endregion }
settings.config的内容实例
<?xml version='1.0' encoding='utf-8'?> <settings> <logger> <loglevel>0</loglevel> <savepath>d:\log</savepath> </logger> <queryurl>http://11.56.254.234:88/shashachaxunserver/shashachaxun</queryurl> <receiveurl>http://172.16.1.131:88/thirdpay/chinaums/xml.aspx</receiveurl> <turnurl>http://172.16.1.131:88/thirdpay/chinaums/query.aspx</turnurl> </chinaums> </settings>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
上一篇: 给妈磕头就知足了