官方建议: - SqlSugarClient 超高性能模式 - 每次 new 创建实例 - IsAutoCloseConnection=true 自动关闭连接 - 适合 DI Scoped 注入、后台任务、Task.Run 场景 修改: 1. DI 注入改为 Scoped(每次 HTTP 请求一个实例) 2. 移除 SqlSugarScope,统一使用 SqlSugarClient 3. 后台任务创建新实例(已实现) 4. MySQL 连接池复用底层 TCP 连接 优点: - 性能更好 - 代码更简单 - 符合官方最佳实践
84 lines
2.9 KiB
C#
Executable File
84 lines
2.9 KiB
C#
Executable File
using SqlSugar;
|
||
using Microsoft.Extensions.Configuration;
|
||
|
||
namespace AssetManager.Data;
|
||
|
||
public static class SqlSugarConfig
|
||
{
|
||
private static IConfiguration? _configuration;
|
||
|
||
/// <summary>
|
||
/// 初始化配置(在Program.cs中调用)
|
||
/// </summary>
|
||
public static void Initialize(IConfiguration configuration)
|
||
{
|
||
_configuration = configuration;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取 SqlSugarClient 实例(超高性能模式)
|
||
/// 每次 new 创建实例,IsAutoCloseConnection=true 自动关闭连接
|
||
/// 适合:DI Scoped 注入、后台任务、Task.Run 场景
|
||
/// </summary>
|
||
public static ISqlSugarClient GetSqlSugarClient()
|
||
{
|
||
if (_configuration == null)
|
||
{
|
||
throw new InvalidOperationException("SqlSugarConfig has not been initialized. Call Initialize() first.");
|
||
}
|
||
|
||
var connectionString = GetConnectionString();
|
||
|
||
// SqlSugarClient 超高性能模式
|
||
// 每次创建新实例,IsAutoCloseConnection=true 确保连接自动关闭
|
||
return new SqlSugarClient(new ConnectionConfig()
|
||
{
|
||
ConnectionString = connectionString,
|
||
DbType = DbType.MySql,
|
||
IsAutoCloseConnection = true, // 必须为 true
|
||
InitKeyType = InitKeyType.Attribute,
|
||
ConfigureExternalServices = new ConfigureExternalServices
|
||
{
|
||
EntityService = (property, column) =>
|
||
{
|
||
if (property.PropertyType == typeof(DateTime))
|
||
{
|
||
column.DataType = "datetime(3)";
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
private static string GetConnectionString()
|
||
{
|
||
var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings__Default")
|
||
?? _configuration!.GetConnectionString("Default")
|
||
?? throw new InvalidOperationException("Connection string 'Default' not found in environment variables or configuration.");
|
||
|
||
// MySQL 连接池优化配置
|
||
if (!connectionString.Contains("Pooling=", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
connectionString += ";Pooling=true";
|
||
}
|
||
if (!connectionString.Contains("MaximumPoolSize=", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
connectionString += ";MaximumPoolSize=100";
|
||
}
|
||
if (!connectionString.Contains("MinimumPoolSize=", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
connectionString += ";MinimumPoolSize=5";
|
||
}
|
||
if (!connectionString.Contains("ConnectionTimeout=", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
connectionString += ";ConnectionTimeout=30";
|
||
}
|
||
if (!connectionString.Contains("ConnectionIdleTimeout=", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
connectionString += ";ConnectionIdleTimeout=180";
|
||
}
|
||
|
||
return connectionString;
|
||
}
|
||
}
|