指定配置文件的监控实现,配置改变了立刻取得最新配置并使用

//以下代码实现的功能:程序自动创建配置文件,并且在配置文件的内容发生变化时立刻更新程序关联的配置类,使得程序在调用配置类时取得的是最新的配置内容,无需重启程序。

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-01\SQL1;Initial Catalog={dbName};uid=TCITClient;pwd=B532!!;";
#if DEBUG
                this.MailServiceUrl = "http://ip2:8001/api/MailService";
                this.ConnectionString = @"Data Source=CL01-SQL-01\SQL1;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; }
    }
}

原文地址:https://www.cnblogs.com/itjeff/p/12230543.html

时间: 2024-10-14 12:01:20

指定配置文件的监控实现,配置改变了立刻取得最新配置并使用的相关文章

来自Killer内核配置改变的威胁–Swappiness

我们受到非黑客攻击,是Linux内核版本3.5-rc1以及RedHat backport补丁应对swappiness=0.这是一种真实的威胁,我们一名客户受到影响,被利用OOM机制使得MySQL主数据库服务器崩溃.这个对内核的"微小"改变导致系统不能适当进行Swap,直接导致OOM机制杀掉MySQL进程.这就对如下解释产生怀疑:系统已拥有128GB内存,很多内存处于空闲状态,同时拥有128GB的空闲虚拟内存,所以在任何情况下都不该启动OOM机制. 我们本以为原因是NUMA(以前写过关于

SpringBoot系列四:SpringBoot开发(改变环境属性、读取资源文件、Bean 配置、模版渲染、profile 配置)

1.概念 SpringBoot 开发深入 2.具体内容 在之前已经基本上了解了整个 SpringBoot 运行机制,但是也需要清楚的认识到以下的问题,在实际的项目开发之中,尤其是 Java 的 MVC 版项目里面,所有的项目都一定需要满足于如下几点要求: · 访问的端口不能够是 8080,应该使用默认的 80 端口: · 在项目之中为了方便进行数据的维护,建议建立一系列的*.properties 配置文件,例如:提示消息.跳转路径: · 所有的控制器现在都采用了 Rest 风格输出,但是正常来讲

19.12 添加自定义监控项目;19.13,19.14 配置邮件告警(上下);19.15 测试告警

19.12 添加自定义监控项目 需求:监控某台web的80端口连接数,并出图 两步:1)zabbix监控中心创建监控项目: 2)针对该监控项目以图形展现 客户端hao2机器配置: 1. 客户端(hao2)编写estab.sh脚本 : [[email protected] ~]# vim /usr/local/sbin/estab.sh 添加内容 : #!/bin/bash ##获取80端口并发连接数 netstat -ant |grep ':80 ' |grep -c ESTABLISHED 2

Spring Boot? 配置文件详解:自定义属性、随机数、多环境配置等

自定义属性与加载 我们在使用Spring Boot的时候,通常也需要定义一些自己使用的属性,我们可以如下方式直接定义: application-dev.yml com.didispace.blog: name: 程序猿DD title: Spring Boot教程 desc: ${com.didispace.blog.name}正在努力写<${com.didispace.blog.title}> # 随机字符串 value: ${random.value} # 随机int number: ${

使用maven profile指定配置文件打包适用多环境

新建maven项目,   在pom.xml中添加 profile节点信息如下: <profiles> <profile> <!-- 开发环境 --> <id>dev</id> <properties> <environment>development</environment><!-- 节点名字environment是自己随意取的 --> </properties> <activa

【Log】logback指定配置文件(二)

摘自:https://www.cnblogs.com/h--d/p/5671528.html [Log]logback指定配置文件(二) 通常我们在不同的环境使用不同的日志配置文件,本章讲指定logback的配置文件,如何使用logback参照[Log]logback的配置和使用(一) 写一个配置加载类,注意JoranConfigurator这个导入的是ch.qos.logback.classic.joran.JoranConfigurator包下面的 1 package com.test; 2

springboot打包去除资源文件及启动时指定配置文件位置

springboot打包时,去掉资源文件,可按照如下配置 <build> <resources> <resource> <directory>src/main/resources</directory> <excludes> <exclude>*.properties</exclude> <exclude>*.log4j2.xml</exclude> </excludes>

3springboot:springboot配置文件(外部配置加载顺序、自动配置原理,@Conditional)

1.外部配置加载顺序 SpringBoot也可以从以下位置加载配置: 优先级从高到低 高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置  1.命令行参数 所有的配置都可以在命令行上进行指定 先打包在进行测试 java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc 指定访问的路径 多个配置用空格分开: --配置项=值 -- 由jar包外向jar包

Android-Activity配置改变

Android-Activity配置改变 一 常见的配置改变 1 横屏竖屏转换 2 语言的改变 3 输入法的有效性切换 二 调用的重要的方法 1 @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); } 2 manifest文件中的<activity and