自定义.net6配置中心中偏平数据解释(如:json对象、数组,字符串)

using System.Text.Json;
namespace Zack.AnyDBConfigProvider
{
static class JsonElementExtensions
{
public static string GetValueForConfig(this JsonElement e)
{
if(e.ValueKind== JsonValueKind.String)
{
//remove the quotes, "ab"-->ab
return e.GetString();
}
else if (e.ValueKind == JsonValueKind.Null
|| e.ValueKind == JsonValueKind.Undefined)
{
//remove the quotes, "null"-->null
return null;
}
else
{
return e.GetRawText();
}
}
}
}using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Text.Json;
using System.Threading;
namespace Zack.AnyDBConfigProvider
{
public class DBConfigurationProvider : ConfigurationProvider,IDisposable
{
private DBConfigOptions options;
//allow multi reading and single writing
private ReaderWriterLockSlim lockObj = new ReaderWriterLockSlim();
private bool isDisposed=false;
public DBConfigurationProvider(DBConfigOptions options)
{
this.options = options;
TimeSpan interval = TimeSpan.FromSeconds(3);
if(options.ReloadInterval!=null)
{
interval = options.ReloadInterval.Value;
}
if (options.ReloadOnChange)
{
ThreadPool.QueueUserWorkItem(obj => {
while (!isDisposed)
{
Load();
Thread.Sleep(interval);
}
});
}
}
public void Dispose()
{
this.isDisposed = true;
}
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();
}
}
public override void Load()
{
base.Load();
IDictionary<string, string> clonedData=null;
try
{
lockObj.EnterWriteLock();
clonedData = Data.Clone();
string tableName = options.TableName;
Data.Clear();
using (var conn = options.CreateDbConnection())
{
conn.Open();
DoLoad(tableName, conn);
}
}
catch(DbException)
{
//if DbException is thrown, restore to the original data.
this.Data = clonedData;
throw;
}
finally
{
lockObj.ExitWriteLock();
}
//OnReload cannot be between EnterWriteLock and ExitWriteLock, or "A read lock may not be acquired with the write lock held in this mode" will be thrown.
if (Helper.IsChanged(clonedData, Data))
{
OnReload();
}
}
private void DoLoad(string tableName, System.Data.IDbConnection conn)
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = $"select Name,Value from {tableName} where Id in(select Max(Id) from {tableName} group by Name)";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string name = reader.GetString(0);
自定义.net6配置中心中偏平数据解释(如:json对象、数组,字符串)
using System.Text.Json;namespace Zack.AnyDBConfigProvider{ static class JsonElementExtensions { public static string ...
点击下载文档文档为doc格式
声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
上一篇
已经是第一篇



