javascript - 在node-express应用程序中使用node-mysql建立共享连接

标签 javascript mysql node.js express node-mysql

目前,我没有在我的设置中使用连接池,因为我的应用程序中只有 1-4 个用户。

根据doc这是推荐的方式。

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connection.threadId);
});

现在,我所做的就是导出连接对象并将其共享给其他 api 资源。

db.js文件上

var mysql      = require('mysql');
var connection = mysql.createConnection({ ... });

module.exports = connection;

api.js 文件上

const express = require('express');
const router = express.Router();

const conn = require('./db');

router.post('/create', function (req, res) {
    connection.query('INSERT ...', function (error, results, fields) {
        if (error) throw error;
        // connected!
    });
});


router.post('/update', function (req, res) {
    connection.query('UPDATE SET ...', function (error, results, fields) {
        if (error) throw error;
        // connected!
    });
});

等等这些示例中省略的其他 api 资源也是如此。

这种连接设计有什么缺点?

最佳答案

如有错误,请指正。我认为,即使您导出连接对象,您仍然在一一管理连接。

Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources Wikipedia

并且来自相同的 doc ,

This is because two calls to pool.query() may use two different connections and run in parallel

所以最好的方法是使用池来管理连接

Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.

希望有帮助。

关于javascript - 在node-express应用程序中使用node-mysql建立共享连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49727972/

相关文章:

javascript - 从数组中找到向下最接近不同数字的数字

javascript - 将函数添加到另一个函数 JavaScript 的范围

javascript - Node.js 类递归发射

java - 如何在 hibernate 中映射两个不相关的类

javascript - 使用meteor.js 分发cocoa 应用程序

javascript - 我想在点击选择大学后显示我的模态框,怎么办?

MySQL结合两个具有相同结构的查询并添加列

mysql - 按天对记录进行分组,包括在 MySQL 中不包含记录的天数

java - 将 HMAC-SHA1 从 node.js 转换为 Java

node.js - 如何在 Node 中获取格式为 "2014-04-01:08:00:00"的当前日期时间?