指定配置文件的监控实现,配置改变了立刻取得最新配置并使用
Posted itjeff
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了指定配置文件的监控实现,配置改变了立刻取得最新配置并使用相关的知识,希望对你有一定的参考价值。
//以下代码实现的功能:程序自动创建配置文件,并且在配置文件的内容发生变化时立刻更新程序关联的配置类,使得程序在调用配置类时取得的是最新的配置内容,无需重启程序。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace xxxxx.MessageHandling.Config { public class MessageHandlerConfig { public MessageHandlerConfig() { var dir = AppDomain.CurrentDomain.BaseDirectory + "Config\"; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); this.ConfigFilePath = AppDomain.CurrentDomain.BaseDirectory + "Config\messageHandler.config"; if (!File.Exists(this.ConfigFilePath)) { this.MailServiceUrl = "http://ip1:8001/api/MailService"; this.ConnectionString = @"Data Source=CL01-SQL-01SQL1;Initial Catalog={dbName};uid=TCITClient;pwd=B532!!;"; #if DEBUG this.MailServiceUrl = "http://ip2:8001/api/MailService"; this.ConnectionString = @"Data Source=CL01-SQL-01SQL1;Initial Catalog={dbName};uid=demo;pwd=demo;"; #endif this.SendMailType = 0; this.saveConfig(); } else { this.readConfig(); } this.configFileLastWriteTime = new FileInfo(this.ConfigFilePath).LastWriteTime; FileSystemWatcher fsw = new FileSystemWatcher(dir); fsw.NotifyFilter = NotifyFilters.LastWrite; fsw.Filter = "messageHandler.config"; fsw.Changed += Fsw_Changed; fsw.EnableRaisingEvents = true; } private void Fsw_Changed(object sender, FileSystemEventArgs e) { if (e.ChangeType != WatcherChangeTypes.Changed) return; var lastUpdateTime = new FileInfo(e.FullPath).LastWriteTime; if (lastUpdateTime == this.configFileLastWriteTime) return; else this.configFileLastWriteTime = lastUpdateTime; Console.WriteLine("Config File Update: " + lastUpdateTime); this.readConfig(); } /// <summary> /// 配置文件路径 /// </summary> protected string ConfigFilePath { get; set; } /// <summary> /// 配置文件最后一次修改时间 /// </summary> private DateTime configFileLastWriteTime { get; set; } /// <summary> /// 发送邮件的方式: /// 0 - 直接始用SMTP方式发送 /// 1 - 通过调用邮件服务发送 /// </summary> public byte SendMailType { get; protected set; } /// <summary> /// 邮件服务的url地址 /// </summary> public string MailServiceUrl { get; protected set; } /// <summary> /// 数据库链接字符串 /// </summary> protected string ConnectionString { get; set; } private bool _isUploadMailTemplates; /// <summary> /// 是否有将邮件模板上传到数据库过 /// </summary> public bool IsUploadMailTemplates { get { return _isUploadMailTemplates; } set { if (value != _isUploadMailTemplates) { _isUploadMailTemplates = value; this.saveConfig(); } } } /// <summary> /// 获取数据库链接字符串 /// </summary> /// <param name="dbName"></param> /// <returns></returns> public string GetConnectionString(string dbName) { return this.ConnectionString.Replace("{dbName}", dbName); } private void readConfig() { FileStream fs = null; StreamReader sr = null; try { if (!File.Exists(this.ConfigFilePath)) return; fs = new FileStream(this.ConfigFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); sr = new StreamReader(fs, Encoding.UTF8); while (!sr.EndOfStream) { var str = sr.ReadLine(); var arr = str.Split(new char[] { ‘=‘ }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length > 1) { try { var name = arr[0]; var val = this.mergeArray(arr, 1, ‘=‘); if (string.Equals(name, "IsUploadMailTemplates", StringComparison.OrdinalIgnoreCase)) this._isUploadMailTemplates = bool.Parse(val); if (string.Equals(name, "SendMailType", StringComparison.OrdinalIgnoreCase)) this.SendMailType = byte.Parse(val); else if (string.Equals(name, "ConnectionString", StringComparison.OrdinalIgnoreCase)) this.ConnectionString = val; else if (string.Equals(name, "MailServiceUrl", StringComparison.OrdinalIgnoreCase)) this.MailServiceUrl = val; } catch { } } } sr.Close(); fs.Close(); } catch { } finally { this.dispose(new IDisposable[] { sr, fs }); } } private string mergeArray(string[] array, int startIndex, char splitChar) { var sb = new StringBuilder(); if (array != null) { for (var i = startIndex; i < array.Length; i++) { if (i == startIndex) sb.Append(array[i]); else sb.Append(splitChar + array[i]); } } return sb.ToString(); } private void saveConfig() { FileStream fs = null; StreamWriter sw = null; try { if (!File.Exists(this.ConfigFilePath)) fs = new FileStream(this.ConfigFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); else fs = new FileStream(this.ConfigFilePath, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite); sw = new StreamWriter(fs, Encoding.UTF8); var sb = new StringBuilder(); sb.AppendLine($"IsUploadMailTemplates={IsUploadMailTemplates}"); sb.AppendLine($"SendMailType={SendMailType}"); sb.AppendLine($"MailServiceUrl={MailServiceUrl}"); sb.AppendLine($"ConnectionString={ConnectionString}"); sw.Write(sb.ToString()); sw.Flush(); fs.Flush(); sw.Close(); fs.Close(); } catch { } finally { this.dispose(new IDisposable[] { sw, fs }); } } private void dispose(IDisposable[] objs) { if (objs != null && objs.Length > 0) { for (var i = 0; i < objs.Length; i++) { var obj = objs[i]; try { if (obj != null) obj.Dispose(); } catch { } finally { obj = null; } } } } private void output() { Console.WriteLine("==============="); Console.WriteLine($"IsUploadMailTemplates={IsUploadMailTemplates}"); Console.WriteLine($"SendMailType={SendMailType}"); Console.WriteLine($"MailServiceUrl={MailServiceUrl}"); Console.WriteLine($"ConnectionString={ConnectionString}"); } } }
调用上面代码的地方
/// <summary> /// 消息处理器 /// </summary> public static class MessageHandler { private static readonly MessageHandlerConfig config = null; static MessageHandler() { try { config = new MessageHandlerConfig(); uploadMailTemplates(); } catch { } } private static void uploadMailTemplates() { if (config == null) return; if (config.IsUploadMailTemplates) return; //异步执行邮件保存 Thread th = new Thread(new ThreadStart(() => { try { var hostName = Environment.UserDomainName + "\" + Environment.MachineName + "\" + Environment.UserName; var baseDir = AppDomain.CurrentDomain.BaseDirectory; var dir = new System.IO.DirectoryInfo(baseDir + "Config"); var files = dir.GetFiles("MessageHandling*.xml"); var list = new List<MessageHandlingData>(); if (files == null || files.Length == 0) return; foreach (var f in files) { var languageCode = string.Empty; var arrFileNames = f.Name.Split(new char[] { ‘.‘ }, StringSplitOptions.RemoveEmptyEntries); if (arrFileNames.Length == 3) languageCode = arrFileNames[1]; if (arrFileNames.Length > 3) continue; FileStream fs = null; StreamReader sr = null; try { fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); sr = new StreamReader(fs, Encoding.UTF8); var strXml = sr.ReadToEnd(); var msgHandling = CommonHelper.DeSerialize<MessageHandlingData>(strXml); foreach (var email in msgHandling.EmailList) { email.ServerName = hostName; email.TemplateFileName = f.Name; email.LanguageCode = languageCode; email.BaseDirectory = baseDir; email.FilePath = f.DirectoryName; } list.Add(msgHandling); foreach (var msgHanding in list) { if (msgHanding == null || msgHanding.EmailList == null) continue; foreach (var mail in msgHanding.EmailList) { if (mail == null) continue; //save mail template to DB CommonHelper.SaveMailTemplate(config.GetConnectionString("TCITLog"), mail); } } } catch (Exception ex) { CommonHelper.WriteLog("保存邮件模板异常啦,method = SaveMailTemplates(), file = " + f.FullName + ", exception = " + ex.ToString()); } finally { if (sr != null) { try { sr.Close(); sr.Dispose(); } catch { } } if (fs != null) { try { fs.Close(); fs.Dispose(); } catch { } } } } config.IsUploadMailTemplates = true; } catch { } })); th.Start(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace xxxx.MessageHandling.Configuration { [XmlRoot("messageHandling", Namespace = "http://tcghl.com/framework/messagehandling")] public class MessageHandlingData { [XmlElement("email")] public List<EmailTempData> EmailList { get; set; } } [Serializable] public class EmailTempData { [XmlAttribute("name")] public string TemplateName { get; set; } [XmlAttribute("subject")] public string Subject { get; set; } [XmlElement("body")] public string Body { get; set; } [XmlIgnore] public string BaseDirectory { get; set; } [XmlIgnore] public string LanguageCode { get; set; } [XmlIgnore] public string TemplateFileName { get; set; } [XmlIgnore] public string FilePath { get; set; } [XmlIgnore] public string ServerName { get; set; } } }
以上是关于指定配置文件的监控实现,配置改变了立刻取得最新配置并使用的主要内容,如果未能解决你的问题,请参考以下文章