Error: Connection lost: The server closed the connection

今天遇到一个问题是shopnc的im没更新已读的消息

在本地别人的机器上没问题,可以修改消息状态,而我机器上不行

输出错误

Error: Connection lost: The server closed the connection.

1
show global variables like '%timeout%';

发现我的wait_timeout 设置的100

而别人的机器是28800

wait_timeout的变量,表示操作超时时间,当连接超过一定时间没有活动后,会自动关闭该连接,这个值默认为28800(即8小时)

1.普通链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
db = mysql.createConnection(db_config.config);
function handleDisconnect() {
    db = mysql.createConnection(db_config.config);
    db.on('error', function(err) {
        if (!err.fatal) {
            return;
        }
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        }else{
            console.log('mysql error: ' + err.code);
            throw err;
        }
    });
    db.connect(function(err) {
        if (err){
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect , 2000);
        }
        console.log('   mysql connected');
    });
}
handleDisconnect();

 2.连接池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var pool = mysql.createPool(db_config.config);
pool.getConnection(function(err, connection) {
    if(err){
        console.log('   mysql-pool connected fail.');
        console.error('   ' + (err.stack || err));
    } else {
        console.log('   mysql-pool connected success.');
    }
});
var query=function(sql,callback){ 
    pool.getConnection(function(err,conn){ 
        if(err){
            console.log('   mysql-pool connected fail.');
            console.error('   ' + (err.stack || err));
            callback(err,null); 
        }else{
            conn.query(sql,function(qerr,vals){ 
                conn.release(); 
                callback(qerr,vals); 
            }); 
        
    }); 
};

  为每一个请求都建立一个connection使用完后调用connection.release(); 直接释放资源

为了提高数据库的IO速度,会使用连接池做处理,但是在高并发的情况下,一条连接完成任务后不释放掉, 会导致链接池满负载 ,后面的请求将无法处理,程序就会出现阻塞

mysql的wait_timeout应设置的小一些

posted @   慕尘  阅读(3922)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示