SqlSugar学习笔记三——配置支持动态分库查询
描述:当程序在在运行时,如何能动态的进行拓展,在不停止程序运行的情况下,通过添加数据库链接到配置文件,实现查询级别的负载均衡?接下来通过一个简单的配置
一、读取配置文件类
public class ConnectionConfigManager
{
private static ConnectionConfig _SqlSugarConnectionConfig = null;
static ConnectionConfigManager()
{
InitSqlSugarConnectionfonfig();
}
public static ConnectionConfig GetConnectionConfigInstance()
{
return _SqlSugarConnectionConfig;
}
/// <summary>
/// 重新读取配置文件里的信息
/// 1.可以监听配置文件,当文件内容改变时进行调用
/// 2.通过手动调用重新加载配置文件
/// </summary>
public void RefreshData()
{
ConnectionConfigManager.InitSqlSugarConnectionfonfig();
ConnectionConfig connection = ConnectionConfigManager.GetConnectionConfigInstance();
}
/// <summary>
/// 这个方法就是初始化_SqlSugarConnectionConfig 字段中的内容
/// </summary>
public static void InitSqlSugarConnectionfonfig()
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
CustomConnectionConfig customConnectionConfig = new CustomConnectionConfig();
configuration.Bind("ConnectionConfig", customConnectionConfig);
ConnectionConfig connection = new ConnectionConfig()
{
DbType = DbType.SqlServer,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
};
connection.ConnectionString = customConnectionConfig.ConnectionString;
List<SlaveConnectionConfig> slaveConnectionList = new List<SlaveConnectionConfig>();
foreach (var SlaveConnection in customConnectionConfig.SlaveConnectionConfigs!)
{
slaveConnectionList.Add(new SlaveConnectionConfig()
{
ConnectionString = SlaveConnection.ConnectionString,
HitRate = 10
});
}
connection.SlaveConnectionConfigs = slaveConnectionList;
_SqlSugarConnectionConfig = connection;
}
}
public class CustomConnectionConfig
{
/// <summary>
/// 主库链接
/// </summary>
public string? ConnectionString { get; set; }
/// <summary>
/// 从库链接
/// </summary>
public List<CustomSlaveConnectionConfig>? SlaveConnectionConfigs { get; set; }
}
public class CustomSlaveConnectionConfig
{
public string? ConnectionString
{
get;
set;
}
}
二、读取配置文件
ConnectionConfig connectionConfig = ConnectionConfigManager.GetConnectionConfigInstance();
三、重新加载配置文件
ConnectionConfigManager.RefreshData();
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16463975.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。
![](https://images.cnblogs.com/cnblogs_com/wml-it/2196906/o_230823011905_wxgzhss.png)