调用函数并在mysql中插入并行节点js

kcugc4gi  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(207)

是否存在如何从外部数据源并行插入数据的方法?这意味着我有多个API/端点,这些API/端点提供了将插入数据库的类似数据集。
例如:

我当前的代码在每个api中循环,并将其保存到数据库中。我的目标行为是上面的图像,希望是动态的。这意味着我可以添加多个端点,并且在调用插入函数时可以并行插入。

lokaqttq

lokaqttq1#

是的,你能做到。
要准备编写代码,明智的做法是在node中使用async/await(即基于promise的api)开发一个mysql 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 */

请注意,此示例代码过于简化,这是危险的。它缺少任何错误或异常处理,这是您在长时间运行的代码中所需要的。

相关问题