解决nodejs mysql Error: Connection lost The server closed the connection

Node连接MySql,会出现几分钟无动作则自动关闭连接,导致Node服务器Down掉。
报错信息:
解决nodejs mysql Error: Connection lost The server closed the connection_第1张图片
解决方法:将sql文件修改为连接池的写法,查询语句也是。
参考链接:https://www.npmjs.com/package/mysql2
具体实现:
原连接写法(db.js):写法没错,但因为数据库无操作断开机制所以还是有问题。看了其他的博客,尝试做了异常处理,还是会出现报错。

const mysql = require("mysql");
const sqlConfig = {
	host: "localhost",
	user: "root",
	password: "root",
	database: "campus",
};
var connection;

function handleDisconnect() {
	connection = mysql.createConnection(sqlConfig);

	connection.connect(function (err) {
		if (err) {
			console.log("error when connecting to db:", err);
			setTimeout(handleDisconnect, 2000);
		}
	});

	connection.on("error", function (err) {
		console.log("db error", err);
		if (err.code === "PROTOCOL_CONNECTION_LOST") {
			handleDisconnect();
		} else {
			throw err;
		}
	});
}

handleDisconnect();

export default handleDisconnect;

更改后使用连接池的写法:(db.js)

var mysql = require("mysql2");

var pool = mysql.createPool({
	host: "localhost",
	user: "root",
	password: "root",
	database: "campus",
});

module.exports = pool;

在接口中引入:(banner.js)
简单示例,没有做其他数据情况判断

const express = require("express");
const router = express.Router();
var pool = require("../db/sqlpool");

// 查看轮播图数据
router.get("/list", function (req, res, next) {
	pool.getConnection(function (err, connection) {
		if (err) throw err;

		connection.query("select * from banner", function (error, result) {
			if (error) throw error;
			var results = result || "{}";
			res.send({
				code: "200",
				message: "查看轮播图数据-admin",
				data: results,
			});
		});
		connection.release();
	});
});
module.exports = router;

经过接口测试,联通稳定,没有再自动断开。

你可能感兴趣的:(node,mysql,javascript,node.js,数据库)