AppSettings从数据库读取

     /// <summary>
/// 提供对配置信息的访问
/// </summary>
public static class AppSettings
{
/// <summary>
/// 配置信息
/// </summary>
private static volatile NameValueCollection _appSettingsCollection; /// <summary>
/// 配置信息属性
/// </summary>
private static NameValueCollection AppSettingsCollection
{
get
{
return _appSettingsCollection ?? ReloadAppSettings();
}
} /// <summary>
/// 重新加载配置信息
/// </summary>
/// <returns></returns>
static NameValueCollection ReloadAppSettings()
{
var nameValueCollection = new NameValueCollection();
//从数据库读取配置
xxx.ToList()
.ForEach(entity =>
{
nameValueCollection[entity.Name] = entity.Value;
});
LastAppSettingsDateTime = DateTime.Now;
_appSettingsCollection = nameValueCollection;
return _appSettingsCollection;
} /// <summary>
/// 在启动时以后台任务刷新配置信息
/// </summary>
static AppSettings()
{
Task.Factory.StartNew(() =>
{
//按配置间隔分钟刷新配置信息
for (; ; )
{
try
{
//取配置的间隔分钟,默认为1分钟
double minutes;
if (_appSettingsCollection == null
|| !double.TryParse(_appSettingsCollection["AppSettingsRefreshIntervalMinutes"], out minutes)
|| minutes < 0.1)
minutes = 1D; Task.Delay(TimeSpan.FromMinutes(minutes)).Wait();
ReloadAppSettings();
}
catch (Exception ex)
{
}
}
}, TaskCreationOptions.LongRunning);
} /// <summary>
/// 获取配置信息
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string Get(string name)
{
return AppSettingsCollection[name];
} /// <summary>
/// 最后获取配置信息的时间
/// </summary>
public static DateTime LastAppSettingsDateTime { get; private set; }
}

遇到的问题:对于相同代码多处部署时,AppSettings配置的到处都是,略显冗余混乱。

解决办法:统一配置到数据库,方便修改。

效率考虑:增加一层静态缓存,采用定时刷新策略。

上一篇:DBC文件小结


下一篇:【Oracle】ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired