关于 SqlSugar 单例模式的问题:
idea-zone opened this issue · comments
idea-zone commented
单例的具体代码
在下面代码中,使用 SqlSugarScope 会出现 下面错误,当把 isScope 修改为 true 时(用 SqlSugarClient) 不会出现下面常见。
场景时: 前端读取上传文件列表,循环请求后端api,解析文件并存储到数据库中。
但是,使用 SqlSugarClient 会出现一些偶发性错误。
版本: .NET 5
浏览器: Chrome 117.0.5938.89
SqlSugarCore 版本: 5.1.4.86
中文提示 : 连接数据库过程中发生错误,检查服务器是否正常连接字符串是否正确,错误信息:53300: sorry, too many clients alreadyDbType="PostgreSQL";ConfigId="304bac51-6781-4b18-be01-784e67646c34". English Message : Connection open error . 53300: sorry, too many clients alreadyDbType="PostgreSQL";ConfigId="304bac51-6781-4b18-be01-784e67646c34"
// 在代码中调用的方式 (所有地方的使用都是 PgFactory.Create() 开头的【旧代码残留的写法】)
PgFactory.Create().ExcuteSQL("insert into SQL 语句");
// 工厂类
public static class PgFactory
{
private static string connString = $"Host={ConfigUtil.PgHost}; Port={ConfigUtil.PgPort};User ID={ConfigUtil.PgUserName};Password={ConfigUtil.PgPassword};Database={ConfigUtil.PgDatabase};";
public static IPostgreSQLHelper Create()
{
//return UsePostgreSQLHelper();
return UseSugarPgSQLHepler();
}
/// <summary>
/// 添加其他过滤项
/// </summary>
/// <returns></returns>
public static IPostgreSQLHelper UseSugarPgSQLHepler()
{
var sugarPgSQLHepler = new SugarPgSQLHepler(PgFactory.connString);
return sugarPgSQLHepler;
}
}
// 封装单例
public class SugarPgSQLHepler : IPostgreSQLHelper,IDisposable{
private static ISqlSugarClient _client;
private string strConn = string.Empty; //连接字符串
private string oldstrConn = null; //连接字符串
private bool _isScope = true;
public object Context { get => _client; }
public SugarPgSQLHepler(string strConn, bool isScope = true)
{
_isScope = isScope;
if (_isScope)
{
// 如果链接字符串被修改了,关闭当前的,实际上,整个程序只会使用一个 strConn,不存在运行时切换 strConn 的情况。
if (oldstrConn != strConn)
{
oldstrConn = this.strConn;
this.strConn = strConn;
_client?.Close();
_client = null;
}
}
else
{
_client = new SqlSugar.SqlSugarClient(new ConnectionConfig()
{
DbType = SqlSugar.DbType.PostgreSQL,
ConnectionString = strConn,
IsAutoCloseConnection = true,
});
// 对 _client 进行一些额外的配置 : 比如设置输出日志等
}
// 在 isScope 模式下,SqlSugarScope 只会被创建一次
if (_client == null)
{
Log.LogFactory.Create().Info(true, "创建数据库连接");
_client = new SqlSugar.SqlSugarScope(new ConnectionConfig()
{
DbType = SqlSugar.DbType.PostgreSQL,
ConnectionString = strConn,
IsAutoCloseConnection = true,
});
// 对 _client 进行一些额外的配置 : 比如设置输出日志等
}
// 其他一些对 SqlSugar 的封装,比如下面这些接口
public DataTable GetDataTable(string strSQL){}
public int ExcuteSQL(string strSQL){}
}
果糖网 commented
果糖网 commented
123456 按着改就行了
果糖网 commented
还有疑问提供可以重现DEMO发我 610262374@qq.com
果糖网 commented
单例后字符串不能修改 需要修改看多租户
idea-zone commented
感谢,已解决。Controller 有些是 async 有些不是。使用 SqlSugarScope + CopyNew 处理了。