通过自定义ConfigurationProvider可以实现从数据库获取参数,
同时读取配置仍然可以使用原本的IConfiguration
添加ConfigProvider 处理加载配置及定期刷新配置逻辑
/// <summary>
/// 配置提供者
/// </summary>
public class ConfigProvider : ConfigurationProvider, IDisposable
{
private bool isDisposed = false;
public ConfigProvider()
{
//定时刷新配置
ThreadPool.QueueUserWorkItem(obj =>
{
while (!isDisposed)
{
Load();
Thread.Sleep(3 * 1000);
}
});
}
/// <summary>
/// 读写锁
/// </summary>
private ReaderWriterLockSlim lockObj = new ReaderWriterLockSlim();
public override IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string parentPath)
{
lockObj.EnterReadLock();
try
{
return base.GetChildKeys(earlierKeys, parentPath);
}
finally
{
lockObj.ExitReadLock();
}
}
public override bool TryGet(string key, out string value)
{
lockObj.EnterReadLock();
try
{
return base.TryGet(key, out value);
}
finally
{
lockObj.ExitReadLock();
}
}
/// <summary>
/// 更新数据
/// </summary>
public override void Load()
{
try
{
lockObj.EnterWriteLock();
//加载配置,可以使用数据库
var config = new
{
AliOSSConfig = "127",
Port="1515"
};
Data["ReRoutesConfig"] = JsonConvert.SerializeObject(config);
}
finally
{
lockObj.ExitWriteLock();
}
OnReload();
}
public void Dispose()
{
isDisposed = true;
}
}
添加配置源继承IConfigurationSource,后续注入时需要使用此类型
/// <summary>
/// 配置源
/// </summary>
public class ConfigSource : IConfigurationSource
{
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new ConfigProvider();
}
}
添加扩展方法
public static class ConfigEx
{
/// <summary>
/// 自定义扩展,增加配置
/// </summary>
public static IConfigurationBuilder AddCustomConfig(this IConfigurationBuilder builder, IConfiguration configuration = null)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return builder.Add(new ConfigSource());
}
}
startup中加载动态配置
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(conf =>
{
conf.AddCustomConfig();
})
测试使用
//configuration通过依赖注入获取 IConfiguration configuration;
var Endpoint = configuration.GetValue<string>("ReRoutesConfig");
标签:lockObj,return,builder,配置,new,net5,动态,public
From: https://www.cnblogs.com/ives/p/18186309