using System.Collections.Concurrent;
using System.IO;
using System.Text.Json;
using GFramework.Core.Abstractions.configuration;
using GFramework.Core.Abstractions.events;
using GFramework.Core.Abstractions.logging;
using GFramework.Core.logging;
namespace GFramework.Core.configuration;
///
/// 配置管理器实现,提供线程安全的配置存储和访问
/// 线程安全:所有公共方法都是线程安全的
///
public class ConfigurationManager : IConfigurationManager
{
///
/// Key 参数验证错误消息常量
///
private const string KeyCannotBeNullOrEmptyMessage = "Key cannot be null or whitespace.";
///
/// Path 参数验证错误消息常量
///
private const string PathCannotBeNullOrEmptyMessage = "Path cannot be null or whitespace.";
///
/// JSON 参数验证错误消息常量
///
private const string JsonCannotBeNullOrEmptyMessage = "JSON cannot be null or whitespace.";
///
/// 配置存储字典(线程安全)
///
private readonly ConcurrentDictionary _configs = new();
private readonly ILogger _logger = LoggerFactoryResolver.Provider.CreateLogger(nameof(ConfigurationManager));
///
/// 用于保护监听器列表的锁
///
private readonly object _watcherLock = new();
///
/// 配置监听器字典(线程安全)
/// 键:配置键,值:监听器列表
///
private readonly ConcurrentDictionary> _watchers = new();
///
/// 获取配置数量
///
public int Count => _configs.Count;
///
/// 获取指定键的配置值
///
public T? GetConfig(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException(KeyCannotBeNullOrEmptyMessage, nameof(key));
if (_configs.TryGetValue(key, out var value))
{
return ConvertValue(value);
}
return default;
}
///
/// 获取指定键的配置值,如果不存在则返回默认值
///
public T GetConfig(string key, T defaultValue)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException(KeyCannotBeNullOrEmptyMessage, nameof(key));
if (_configs.TryGetValue(key, out var value))
{
return ConvertValue(value);
}
return defaultValue;
}
///
/// 设置指定键的配置值
///
public void SetConfig(string key, T value)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException(KeyCannotBeNullOrEmptyMessage, nameof(key));
// 先获取旧值,以便正确检测变更
_configs.TryGetValue(key, out var oldValue);
// 更新配置值
_configs[key] = value!;
// 只有在值真正变化时才触发监听器
if (!EqualityComparer