Node MySQL连接池

编程入门 行业动态 更新时间:2024-10-14 02:22:01

Node MySQL<a href=https://www.elefans.com/category/jswz/34/1766187.html style=连接池"/>

Node MySQL连接池

如何检查MySQL数据库是否已准备好从节点MySQL连接池进行某些查询?

我有一个由您的容器组成的Docker环境:

  • 容器1:Web服务器
  • 容器2:API
  • 容器3:数据库

数据库容器运行一个MySQL数据库。 api容器连接到该数据库。所有三个容器同时启动。 Web服务器容器在0.5秒后启动。 api容器在2秒后启动。 20秒后数据库服务器启动。

当前,api会在数据库启动并运行之前尝试访问数据库的表。这会导致错误,例如拒绝连接。以下代码段始终以消息“错误查询数据库!”结尾。当MySQL数据库尚未启动时:

const sql: string = 'SELECT * FROM sometable;';
MySQL.createPool({
    connectionLimit: 10,
    acquireTimeout: 30000,
    waitForConnections: true,
    database: 'mydatabase',
    host: 'localhost',
    multipleStatements: true,
    password: 'mypassword',
    user: 'root',
}).query(sql, (err, result) => {
    if (result) {
        console.log('Successfully queried database.');
    } else {
        console.log('Error querying database!');
    }
});

正在使用的版本:

OS: Ubuntu 19.10
Node: v13.6.0
MySQL (Node API): "@types/mysql": "2.15.8" and "mysql": "2.17.1"
MySQL (Docker Database): mysql:5.7.28
TypeScript: 3.7.4

我想从api中检查(并等待)数据库的就绪状态,可能使用我用于查询的连接池。有可能吗?

回答如下:

尝试重新连接setTimeout()

(用JavaScript而不是打字稿回答)

'use strict';

const dbpool = require('mysql').createPool({
    connectionLimit: 10,
    acquireTimeout: 30000,
    waitForConnections: true,
    database: 'mydatabase',
    host: 'localhost',
    multipleStatements: true,
    password: 'mypassword',
    user: 'root',
});

const sql = 'SELECT * FROM sometable;';

const attemptConnection = () =>
  dbpool.getConnection((err, connection) => {
  if (err) {
    console.log('error connecting. retrying in 1 sec');
    setTimeout(attemptConnection, 1000);
  } else {
    connection.query(sql, (errQuery, results) => {
      connection.release();
      if (errQuery) {
        console.log('Error querying database!');
      } else {
        console.log('Successfully queried database.');
      }
    });
  }
});

attemptConnection();

这是我的测试运行:

$ sudo service mysql stop; node test.js & sudo service mysql start
[1] 24737
error connecting. retrying in 1 sec
error connecting. retrying in 1 sec
$ Successfully queried database.

FYI,程序永远不会结束,因为它需要dbpool.end();

更多推荐

Node MySQL连接池

本文发布于:2024-05-07 00:15:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753967.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接池   Node   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!