using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using Aitex.Core.RT.Log; using System.IO; using Aitex.Common.Util; using System.Collections.Concurrent; using Aitex.Core.RT.DataCenter; using Aitex.Core.Util; namespace Aitex.Core.RT.ConfigCenter { public class ConfigManager : Singleton, ICommonConfig { Dictionary _dic = new Dictionary(); ConcurrentDictionary> _keyValueMap = new ConcurrentDictionary>(); object _locker = new object(); public ConfigManager() { } public void Initialize() { CONFIG.InnerConfigManager = this; } public void Terminate() { } /// /// 如果文件不存在,返回NULL。如果读取错误,返回"" /// /// /// public string GetFileContent(string fileName) { if (!Path.IsPathRooted(fileName)) fileName = PathManager.GetCfgDir() + "\\" + fileName; if (!File.Exists(fileName)) return null; StringBuilder s = new StringBuilder(); try { using (StreamReader sr = new StreamReader(fileName)) { while (!sr.EndOfStream) { s.Append(sr.ReadLine()); } } } catch (Exception ex) { LOG.Write(ex); return ""; } return s.ToString(); } public object GetConfig(string config) { return _dic.ContainsKey(config) ? _dic[config] : null; } public void SetConfig(string config, object value) { _dic[config] = value; } public void Subscribe(string module, string key, Func getter) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key"); if (!string.IsNullOrEmpty(module)) key = module + "." + key; if (_keyValueMap.ContainsKey(key)) throw new Exception(string.Format("Duplicated Key:{0}", key)); if (getter == null) throw new ArgumentNullException("getter"); _keyValueMap.TryAdd(key, new DataItem(getter)); } public object Poll(string key) { return _keyValueMap.ContainsKey(key) ? _keyValueMap[key].Value : null; } public Dictionary PollConfig(IEnumerable keys) { Dictionary result = new Dictionary(); foreach (string key in keys) { if (_keyValueMap.ContainsKey(key)) result[key] = _keyValueMap[key].Value; else { LOG.Error("未定义的Config:" + key); } } return result; } } }