Bla*_*gas 5 mysql node.js mysql2 typescript node-mysql2
我正在使用 nodejs + mysql2 的项目中工作,有时我收到错误Too muchconnections。
我的连接:
import {createPool, Pool} from 'mysql2/promise';
export async function connect(): Promise < any > {
const connection: Pool = await createPool({
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'mendozarq',
connectionLimit: 10
});
return connection;
}
Run Code Online (Sandbox Code Playgroud)
控制器:
import { Response, Request } from 'express';
import { FieldPacket, Pool } from 'mysql2/promise';
import { connect } from './../../classes/database';
import { Personal } from './../../models/personal.interface';
export const getAllPersonal = async (req: Request, res: Response) => {
try {
const conn: Pool = await connect();
const [personal]: [any[], FieldPacket[]] = await conn.query('SELECT * FROM personal ORDER BY creadoEn DESC');
conn.end();
return res.status(200).json(personal);
} catch (error) {
return res.status(400).json({
error
});
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是我必须使用createConnection而不是createPool,或者我只需要创建我的 conn 的一个实例。
Get*_*awn 12
您应该只调用createPool一次,然后每次都从池中进行选择。
所以,它应该看起来像这样。创建一个存储池的常量。然后在函数中,如果池已经存在,则返回池而不调用createPool。如果它不存在,那么您将调用createPool并返回已创建的池。
import {createPool, Pool} from 'mysql2/promise';
const globalPool: Pool | undefined = undefined;
export async function connect(): Promise <Pool> {
// If the pool was already created, return it instead of creating a new one.
if(typeof globalPool !== 'undefined') {
return globalPool;
}
// If we have gotten this far, the pool doesn't exist, so lets create one.
globalPool = await createPool({
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'mendozarq',
connectionLimit: 10
});
return globalPool;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6322 次 |
| 最近记录: |