有没有办法从外部数据源并行插入数据?这意味着我有多个API/Endpoint,它们提供将要插入到数据库中的相似数据集。
例如:
我当前的代码是遍历每个API并将其保存到数据库中。我的目标行为是上面的图像,希望是动态的。这意味着我可以添加多个端点,并且可以在调用insert函数时并行插入。
发布于 2021-07-12 19:38:25
是的,你可以做到。
为了准备编写代码,明智的做法是在该MySQL节点中创建一个版本的Promise应用编程接口(即基于Promise的works with async/await )。
然后准备好使用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 */
请注意,此示例代码过于简单,这是危险的。它缺少在长时间运行的代码中需要的任何错误或异常处理。
https://stackoverflow.com/questions/68346348
复制相似问题