【问题标题】:create new tedious connection every time for a new API call?每次为新的 API 调用创建新的繁琐连接?
【发布时间】:2021-10-28 19:15:10
【问题描述】:

我正在创建 Express JS 作为我的 API 服务器,使用繁琐的方法连接到我的 SQL Server 数据库。

目前,在每个请求逻辑中,我都会创建一个新的繁琐的 Connection 对象,连接到 DB,执行查询,然后关闭连接。

import { Connection } from 'tedious';
export class Controller {
  all(_: Request, res: Response): void {

    const connection = new Connection(getConfig()); // create a new connection everytime

    connection.on('connect', (err) => {
      if (err) {
        console.log('Connection Failed');
        throw err;
      }
      getProducts(connection, _, res); // in there at the end, will call connection.close()
    });

    connection.connect();
  }
import { Request, Response } from 'express';
import { Connection, Request as SqlReq } from 'tedious';
export default function getProducts(connection: Connection, _: Request, res: Response) {
    const query = `SELECT * FROM Production.Product FOR JSON PATH;`;
    let resultJson = ''; // prepare this result in return from SQL query

    const sqlReq = new SqlReq(query, (err, _) => {
      if (err) {
        throw err;
      }

      // when request finished
      connection.close();
      res.json(JSON.parse(resultJson));
    });

每次为新的 API 调用创建连接、连接和关闭是好还是坏?如果有更好的方法来处理连接,我可以提供任何参考或示例吗?

【问题讨论】:

    标签: node.js express tedious


    【解决方案1】:

    只需确保使用此功能只创建一次连接即可。它将仅在第一次调用时创建连接,并在后续调用时返回先前创建的连接。

    var connection = null;
    const getConnection = async () => {
      if (connection) return connection;
    
      connection = new Connection(getConfig());
      return tmp;
    };
    

    那么你应该通过不调用close来保持连接打开。

    【讨论】:

      【解决方案2】:

      在 mysql 中更好地使用连接池。在应用程序启动期间,您可以创建一个用于连接数据库的线程池。如果您从池中检索并建立连接,它将非常快。 查询执行/操作后,确保释放连接。因此它将进入连接池并可供进一步请求。

      参考:How do I create a MySQL connection pool while working with NodeJS and Express?

      Ref : 释放​​连接 node.js + mysql connection pooling

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多