是的,你可以这样做。
要准备编写代码,明智的做法是在 works with async/await 的节点中构建一个 MySQL API 版本(即基于 Promise 的 API)。
然后工具起来使用一个mysql连接池。您可以限制池中的连接总数。这是明智之举,因为过多的连接可能会使您的 MySQL 服务器不堪重负。
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'host',
user: 'redacted',
database: 'redacted',
waitForConnections: true,
connectionLimit: 6,
queueLimit: 0
})
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
然后将每个 API 访问操作编写为带有循环的异步函数。对于每个 API 操作,即使对于多个顺序查询,这样的东西也会使用一个连接。
async function apiOne(pool) {
while (true) {
const result = await (api_operation)
connection = await pool.getConnection()
const [rows, fields] = await connection.execute(whatever)
const [rows, fields] = await connection.execute(whatever_else)
connection.release()
await sleep(1000) // wait one second
}
}
在循环内部而不是外部执行getConnection()。 Pool.getConnection() 非常快,因为它重用了现有的连接。在循环内执行此操作可以让您的池限制同时连接的数量。
sleep() 函数当然是可选的。您可以使用它来控制循环运行的速度。
根据需要编写尽可能多的这些函数。这是处理多个 API 的好方法,因为每个 API 的代码都在自己的函数中隔离。
最后,使用Promise.all() 同时运行所有异步函数。
const concurrents = []
concurrents.push (apiOne(pool))
concurrents.push (apiTwo(pool))
concurrents.push (apiThree(pool))
Promise.all (concurrents).then() /* run all the ApiXxx functions */
请注意,此示例代码过于简单化了很危险。它缺少长时间运行代码中需要的任何错误或异常处理。