简体   繁体   English

在 Discord bot 开启约 12 小时后,MySQL 自行关闭

[英]MySQL turns itself off after discord bot left on for about 12 hours

I'm hosting a discord.js bot on an ubuntu VPS, and the bot uses MySQL as its database.我在 ubuntu VPS 上托管了一个 discord.js 机器人,该机器人使用 MySQL 作为其数据库。 I turn on the bot, and leave it, and it works fine, but after about 12 hours (it tends to vary), the bot goes offline, because of an error, saying MySQL server disconnected.我打开机器人,然后离开,它工作正常,但大约 12 小时后(它往往会有所不同),机器人离线,因为出现错误,说 MySQL 服务器断开连接。 But, if I restart the bot, MySQL turns back on, and bits of the bot that require the database use the database perfectly fine.但是,如果我重新启动机器人,MySQL 会重新打开,并且需要数据库的机器人部分可以完美地使用数据库。 I'm not sure if this is an error with MySQL, Node.JS or Ubuntu, but I don't know how to fix it.我不确定这是否是 MySQL、Node.JS 或 Ubuntu 的错误,但我不知道如何修复它。 Thanks!谢谢!

I had a similar issue when I started using MySQL.当我开始使用 MySQL 时,我遇到了类似的问题。 The problem is that your bot crashes when it encounters a connection timeout.问题是您的机器人在遇到连接超时时会崩溃。 The MySQL server doesn't go offline, just your connection to it does. MySQL 服务器不会脱机,只有您与它的连接才会脱机。 Meaning that when you restart your bot it reconnects and everything works.这意味着当您重新启动机器人时,它会重新连接并且一切正常。

I encountered two ways of getting around the issue of having to restart the bot manually.我遇到了两种解决必须手动重新启动机器人的问题的方法。

  • Set up your bot so that it restarts automatically when it encounters a critical error.设置您的机器人,使其在遇到严重错误时自动重新启动。 (Not really the best option but if you want to do it that way it works) (不是最好的选择,但如果你想这样做的话,它的工作原理)

  • Create a connection pool.创建连接池。

This is by far the better option.这是迄今为止更好的选择。 It will create a pool of connections ready to go.它将创建一个准备就绪的连接池。 When you need a connection it will provide you with one and release it after you are done.当您需要连接时,它会为您提供一个连接并在您完成后释放它。 That way your connection won't time out.这样你的连接就不会超时。

It works like this:它是这样工作的:

const mysql = require('mysql');

var db_config = {
 user: 'root',
 password: 'Your password',
 database: 'Your database',
 // etc
};

var con = mysql.createPool(db_config);

con.getConnection(function(err, con) {
 if (err) {
  connection.release();
  console.log(' Error getting mysql_pool connection: ' + err);
  throw err;
 }
 console.log('Connected to Database');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM