【问题标题】:Call a function and Insert in MySQL Parallel in Node JS在 Node JS 中调用一个函数并在 MySQL Parallel 中插入
【发布时间】:2023-03-23 08:00:01
【问题描述】:

无论如何如何从外部数据源并行插入数据?这意味着我有多个 API/端点,它们提供将插入数据库的类似数据集。

例如:

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

【问题讨论】:

  • mysql 最肯定支持通过多个连接开箱即用的并行数据修改,因此实现它真的取决于您的应用程序逻辑。
  • 嗨@Shadow。感谢回复。我的问题是如何实现这种逻辑。并行调用插入函数。

标签: javascript node.js concurrency sails.js


【解决方案1】:

是的,你可以这样做。

要准备编写代码,明智的做法是在 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 */ 

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

【讨论】:

    猜你喜欢
    • 2020-05-14
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2014-09-21
    相关资源
    最近更新 更多