草庐IT

mysql连接丢失错误nodejs

coder 2023-10-22 原文

我正在使用以下代码将我的 Node 连接到 mysql,用于我在我的项目中使用的所有其余 api; 我已将其作为我所有查询请求的通用数据库连接文件。

var mysql = require('mysql');
var db_connect = (function () {
    function db_connect() {
        mysqlConnConfig = {
            host: "localhost",
            user: "username",
            password: "password",
            database: "db_name"
        };
    }
    db_connect.prototype.unitOfWork = function (sql) {
    mysqlConn = mysql.createConnection(mysqlConnConfig);
        try {
            sql(mysqlConn);
        } catch (ex) {

            console.error(ex);
        } finally {
            mysqlConn.end();
        }
    };
    return db_connect;
})();
exports.db_connect = db_connect;

上面的代码工作正常,我将在我的所有其余 api 中使用我的查询来执行下面的“sql”。

var query1 = "SELECT * FROM table1";
 sql.query(query1,function(error,response){
if(error){
    console.log(error);
}
else{
    console.log(response);
    }
 })

到目前为止一切顺利,但问题是我遇到了 sql 协议(protocol)连接错误 在运行我的 forever 模块 8-12 小时后

forever start app.js

我正在使用上面的 forever 模块开始我的项目。 8-12 小时后,我收到以下错误消息,我所有的其余 API 都无法正常工作或出现故障。

"stack": ["Error: Connection lost: The server closed the connection.", "    at Protocol.end (/path/to/my/file/node_modules/mysql/lib/protocol/Protocol.js:109:13)", "    at Socket.<anonymous> (/path/to/my/file/node_modules/mysql/lib/Connection.js:102:28)", "    at emitNone (events.js:72:20)", "    at Socket.emit (events.js:166:7)", "    at endReadableNT (_stream_readable.js:913:12)", "    at nextTickCallbackWith2Args (node.js:442:9)", "    at process._tickDomainCallback (node.js:397:17)"],
"level": "error",
"message": "uncaughtException: Connection lost: The server closed the connection.",
"timestamp": "2017-09-13T21:22:25.271Z"

然后我在研究中得到了一个解决方案来配置句柄断开连接,如下所示。 但是我正在努力使用我的代码如下配置我的 sql 连接。

var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connection.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

handleDisconnect();

谁能帮我用上面的代码修改我的代码?

最佳答案

SHOW SESSION VARIABLES LIKE '%wait_timeout';
SHOW GLOBAL  VARIABLES LIKE '%wait_timeout';

其中一个设置为 28800(8 小时)。增加它。

或者...捕获错误并重新连接。

或者...检查您的框架中如何处理“连接池”。

但是...请注意,可能会发生网络故障。因此,简单地增加超时并不能解决此类故障。

或者...不要在连接上挂得太久。它不是很好玩。 并且它可能导致超过 max_connections

(抱歉,我对您的应用程序了解得不够深入,无法更具体地说明这些路径中的哪一个。)

最大连接数

...wait_timeoutmax_connections 以笨拙的方式结合在一起。如果超时“太高”,连接数会不断增长,从而威胁到“连接过多”错误。在典型设计中,最好降低超时值以防止客户端浪费时间卡在连接上太久。

如果您的情况是这样的:“固定数量的客户端希望永远保持连接”,则增加超时,但不是max_connections(至少不会超过固定数量的客户)。

不过,如果网络出现故障,连接可能会中断。所以,你仍然可以得到“连接丢失”。 (但是,如果一切都在同一台机器上,这是不太可能的。)

关于mysql连接丢失错误nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260200/

有关mysql连接丢失错误nodejs的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  3. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  4. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  5. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  6. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  7. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  8. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  9. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  10. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

随机推荐