using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using CYQ.Data.Tool;
using CYQ.Data.Json;
namespace CYQ.Data
{
///
/// 链接配置管理
///
internal class ConnConfigWatch
{
///
/// 监控列表。
///
private static MDictionary watchList = new MDictionary();
private static readonly object o = new object();
///
/// 开启加载一个配置。
///
/// Conn的名称
/// Conn指向的路径
///
public static string Start(string connName, string connPath)
{
lock (o)
{
string path = AppConfig.RunPath + connPath;
string json = JsonHelper.ReadJson(path);
if (string.IsNullOrEmpty(json))
{
return connName;
}
WatchConfig config = JsonHelper.ToEntity(JsonHelper.GetValue(json, connName));
if (config != null && !string.IsNullOrEmpty(config.Master))
{
AppConfig.SetConn(connName, config.Master);
if (!string.IsNullOrEmpty(config.Backup))
{
AppConfig.SetConn(connName + "_Bak", config.Backup);
}
if (config.Slave != null && config.Slave.Length > 0)
{
for (int i = 0; i < config.Slave.Length; i++)
{
AppConfig.SetConn(connName + "_Slave" + (i + 1), config.Slave[i]);
}
}
if (!watchList.ContainsValue(connPath))
{
IOWatch.On(path, delegate (FileSystemEventArgs e)
{
fsy_Changed(e);
});
}
if (!watchList.ContainsKey(connName))
{
watchList.Add(connName, connPath);
}
return config.Master;
}
}
return connName;
}
private static void fsy_Changed(FileSystemEventArgs e)
{
string json = JsonHelper.ReadJson(e.FullPath);
Dictionary dic = JsonHelper.Split(json);
if (dic != null && dic.Count > 0)
{
foreach (KeyValuePair item in dic)
{
//移除所有缓存的Key
AppConfig.SetConn(item.Key, null);
AppConfig.SetConn(item.Key + "_Bak", null);
for (int i = 1; i < 1000; i++)
{
if (!AppConfig.SetConn(item.Key + "_Slave" + i, null))
{
break;
}
}
ConnObject.Remove(item.Key);
ConnBean.Remove(item.Key);
}
}
}
}
internal class WatchConfig
{
public string Master;
public string Backup;
public string[] Slave;
}
}