【问题标题】:Using mysql pool with async\await | nodeJS使用带有 async\await 的 mysql 池 |节点JS
【发布时间】:2022-01-22 23:06:01
【问题描述】:

我正在使用 mysql2 和 nodejs,目前使用如下简单连接:

mysql.ts

    const Connect = () => {
  if (!connection)
    return mysql.createConnection(params);
  return connection;
};

someQuery.ts

 const connection = Connect();
    const asyncQuery = util.promisify(connection.query).bind(connection);

现在,在服务器运行应用程序的一段时间后,由于连接丢失而崩溃,我在网上阅读了一些内容,了解到为了解决它,作为更好的做法,我应该使用连接池。 问题是我还没有真正找到像上面那样使用 async-await 的东西。

有人对此有解决方案吗? await asyncQuery('在这里查询');

【问题讨论】:

    标签: mysql node.js connection-pooling mysql2


    【解决方案1】:

    去年我有一个项目,我使用了 mysql2/promise 库。

    connector.js

    const mysql = require('mysql2/promise');
    
    const con = mysql.createPool({
            host: "localhost",
            user: "root",
            password: "pw",
            database: "database",
            waitForConnections: true,
            connectionLimit: 10,
            queueLimit: 0
    
    });
    
    module.exports = con;
    

    queries.js

    const db = require('../helpers/mysql/connector');
    
    getAnything: async () => {
                    try {
                            let anything = await db.execute("SELECT * FROM anything");
                            return colos[0];
                    } catch (e) {
                            console.log(e);
                            return null;
                    }
            },
    

    【讨论】:

    • 嗨,你能分享一下你是如何查询的吗?这只是连接创建。
    猜你喜欢
    • 1970-01-01
    • 2020-02-14
    • 2018-07-15
    • 2020-11-22
    • 2017-06-05
    • 2016-02-02
    • 2019-03-14
    • 2021-09-27
    • 2018-03-09
    相关资源
    最近更新 更多