























环境:.net9+efcore9 + mysql8
测试环境:mysql8 ,win10本地安装
项目:vs2022启动 release 环境
测试工具:jmeter https://www.cnblogs.com/1285026182YUAN/p/19697195
测试需求:500并发
一. 默认配置
mysql8 默认允许的最大连接为 151
.net9 默认的 线程池 较少,
线程池的默认大小并非一个固定值,而是根据你服务器的 CPU 核心数动态计算的
efcore9 默认的
数据库最大连接数(Max Pool Size)为 100
数据库最小连接数(Min Pool Size) 为 0
数据库超时时间(Default Command Timeout) 为 30秒
"Server=localhost;port=3306;Database=high-concurrency;Uid=root;Pwd=123456;SslMode=None;Pooling=True;"
二. 调整
1. 数据库
1) 情况1,临时修改,重启无效
打开mysql命令窗口,开始 - MySQL 8.0 Command Line Clinet
-- 设置最大连接数为 500
SET GLOBAL max_connections = 500;
-- 设置 InnoDB 缓冲池(Buffer Pool)大小 10G
SET GLOBAL innodb_buffer_pool_size = 10737418240;
2) 情况2,修改配置文件,永久生效
打开文件 my.ini,地址:C:\ProgramData\MySQL\MySQL Server 8.0
[mysqld]
# ===== 连接数配置 =====
max_connections = 500
# ===== 内存配置 =====
# InnoDB 缓冲池(根据服务器内存调整,建议 60%-70%)
innodb_buffer_pool_size = 10G
重启服务,任务管理器 - 服务,找到 mysql80 右键 重启
3) 效果查询
-- 查询数据库允许最大连接数
SHOW VARIABLES LIKE 'max_connections';
-- 查询
SHOW VARIABLES LIKE 'innodb_buffer_pool_size';
-- 查询 使用测试过程中 实际的连接数
SHOW STATUS LIKE 'Threads_connected';
2. .net9 项目
1) 配置数据库连接,appsettings.json
数据库最大连接数(Max Pool Size)为 500
数据库最小连接数(Min Pool Size) 为 20
数据库超时时间(Default Command Timeout) 为 120秒
"ConnectionStrings": {
"RailHigh": "Server=localhost;port=3306;Database=high-concurrency;Uid=root;Pwd=123456;SslMode=None;Pooling=True;Max Pool Size=450;Min Pool Size=20;Default Command Timeout=120;"
},
2) 配置线程池,Program.cs
// 放在这里,在所有服务注册之前
builder.WebHost.ConfigureKestrel(options =>
{
options.Limits.MaxConcurrentConnections = 1000;
options.Limits.MaxConcurrentUpgradedConnections = 1000;
options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(120);
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(60);
options.AllowSynchronousIO = false;
});
// 线程池配置放在这里
ThreadPool.SetMinThreads(200, 200);
ThreadPool.SetMaxThreads(1000, 1000);
3) 注意在还原 efcore9 时,加上 -NoOnConfiguring
Scaffold-DbContext -Connection "server=localhost;port=3306;userid=root;password=123456;database=high-concurrency;" -Provider Pomelo.EntityFrameworkCore.MySql -OutputDir Models -ContextDir Context -Context DataBaseHigh -Force -NoOnConfiguring
3. 增加项目连接数监控
1) 增加中间件 Middle/ActiveConnectionCounter.cs
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NETCORE.HighConcurrency.Middleware
{
// ============================================================
// 1. 统计服务
// ============================================================
public class ActiveConnectionCounter
{
private int _current = 0;
private int _peak = 0;
private int _total = 0;
private readonly object _lock = new object();
public void Increment()
{
lock (_lock)
{
_current++;
_total++;
if (_current > _peak) _peak = _current;
}
}
public void Decrement()
{
lock (_lock)
{
_current--;
}
}
public (int current, int peak, int total) GetStats()
{
lock (_lock)
{
return (_current, _peak, _total);
}
}
// ✅ 重置统计
public void Reset()
{
lock (_lock)
{
_current = 0;
_peak = 0;
_total = 0;
}
}
}
// ============================================================
// 2. 中间件
// ============================================================
public class ConnectionCountMiddleware
{
private readonly RequestDelegate _next;
private readonly ActiveConnectionCounter _counter;
public ConnectionCountMiddleware(RequestDelegate next, ActiveConnectionCounter counter)
{
_next = next;
_counter = counter;
}
public async Task InvokeAsync(HttpContext context)
{
_counter.Increment();
try
{
await _next(context);
}
finally
{
_counter.Decrement();
}
}
}
// ============================================================
// 3. 后台打印服务(带交互)
// ============================================================
public class StatsPrintService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IConfiguration _configuration;
private bool _enabled;
private int _intervalSeconds;
private readonly object _lock = new object();
public StatsPrintService(
IServiceProvider serviceProvider,
IConfiguration configuration)
{
_serviceProvider = serviceProvider;
_configuration = configuration;
// 从配置文件读取初始值
_enabled = configuration.GetValue<bool>("ConnectionMonitor:Enabled", true);
_intervalSeconds = configuration.GetValue<int>("ConnectionMonitor:IntervalSeconds", 3);
}
// ✅ 供外部调用的控制方法
public void Enable() { lock (_lock) { _enabled = true; } }
public void Disable() { lock (_lock) { _enabled = false; } }
public void SetInterval(int seconds) { lock (_lock) { _intervalSeconds = Math.Max(1, seconds); } }
public bool IsEnabled() { lock (_lock) { return _enabled; } }
public int GetInterval() { lock (_lock) { return _intervalSeconds; } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// ✅ 启动交互命令监听线程
_ = Task.Run(() => CommandListener(stoppingToken));
Console.WriteLine("[ConnectionMonitor] 交互命令: on(开启), off(关闭), interval=N(间隔秒), stats(查看), reset(重置)");
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(GetInterval() * 1000, stoppingToken);
if (!IsEnabled())
continue;
using var scope = _serviceProvider.CreateScope();
var counter = scope.ServiceProvider.GetRequiredService<ActiveConnectionCounter>();
var (current, peak, total) = counter.GetStats();
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 当前连接数: {current,3} | 峰值: {peak,3} | 总请求: {total,6}");
}
}
// ✅ 命令行监听
private void CommandListener(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var input = Console.ReadLine()?.Trim().ToLower();
if (string.IsNullOrEmpty(input))
continue;
if (input == "on")
{
Enable();
Console.WriteLine($"[ConnectionMonitor] ✅ 已开启打印,间隔 {GetInterval()} 秒");
}
else if (input == "off")
{
Disable();
Console.WriteLine("[ConnectionMonitor] ❌ 已关闭打印");
}
else if (input == "stats")
{
using var scope = _serviceProvider.CreateScope();
var counter = scope.ServiceProvider.GetRequiredService<ActiveConnectionCounter>();
var (current, peak, total) = counter.GetStats();
Console.WriteLine($"[ConnectionMonitor] 📊 当前: {current} | 峰值: {peak} | 总请求: {total}");
}
else if (input == "reset")
{
using var scope = _serviceProvider.CreateScope();
var counter = scope.ServiceProvider.GetRequiredService<ActiveConnectionCounter>();
counter.Reset();
Console.WriteLine("[ConnectionMonitor] 🔄 统计已重置");
}
else if (input.StartsWith("interval="))
{
var parts = input.Split('=');
if (parts.Length == 2 && int.TryParse(parts[1], out int seconds))
{
SetInterval(seconds);
Console.WriteLine($"[ConnectionMonitor] ⏱️ 打印间隔已设为 {seconds} 秒");
}
else
{
Console.WriteLine("[ConnectionMonitor] ❌ 格式错误,示例: interval=5");
}
}
else if (input == "help")
{
PrintHelp();
}
}
}
private void PrintHelp()
{
Console.WriteLine(@"
[ConnectionMonitor] 可用命令:
on - 开启打印
off - 关闭打印
stats - 查看当前统计
reset - 重置统计
interval=N - 设置打印间隔(N 为秒数)
help - 显示帮助
");
}
}
}
2) 中间件注入Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ActiveConnectionCounter>();
builder.Services.AddHostedService<StatsPrintService>();
var app = builder.Build();
app.UseMiddleware<ConnectionCountMiddleware>();
3) 配置文件
"ConnectionMonitor": {
"Enabled": false, // 默认是否监控连接数
"IntervalSeconds": 3 // 初始间隔
}
相关项目: D:\codemyself\NETCOREPROJECT\NETCORE.HighConcurrency
end.
```
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。