我可以使用一个连接到 postgresql 并使用它来进行并发查询吗?
Can I use one connection to postgresql and use it to make concurrent queries?
我用knex在nodejs中写,我想更新数据库中的多行,我想知道我是否可以并行执行多个更新查询,
像这样:
const updatesPromises = books.map((book) =>
transaction('books')
.where({ id: book.id })
.update({ title: book.name }, ['id', 'title'])
await Promise.all(updatesPromises)
改为同步执行每个更新查询,如下所示:
books.forEach(async (book) =>
await transaction('books')
.where({ id: 42 })
.update({ title: "The Hitchhiker's Guide to the Galaxy" }, ['id', 'title'])
transaction
是我之前创建的连接,所有更新后提交
这是最佳做法吗?
大规模会不会出问题?
I wondered if I can execute multiple update queries in parallel
没有。单个连接仅支持顺序执行查询。 node-postgres
不会阻止您一次发出多个调用,但它会在内部对它们进行排队,因此您不会从一次创建所有承诺并对其调用 Promise.all
中获得任何好处。
(也就是说,我不知道 Knex transaction
是如何工作的,如果它使用 connection pool 它实际上可能不会将您限制为单个连接。但是,如果您为多个 HTTP 客户端提供服务,那不是最佳做法,您应该只对每个 HTTP 请求使用连接。)
由于您正在使用事务,因此最佳做法是一个接一个地按顺序进行。
在您的情况下,如果其中一个查询失败,错误处理也非常令人讨厌,但 Promise.all()
可能会继续向已经回滚的事务发送查询。
我用knex在nodejs中写,我想更新数据库中的多行,我想知道我是否可以并行执行多个更新查询,
像这样:
const updatesPromises = books.map((book) =>
transaction('books')
.where({ id: book.id })
.update({ title: book.name }, ['id', 'title'])
await Promise.all(updatesPromises)
改为同步执行每个更新查询,如下所示:
books.forEach(async (book) =>
await transaction('books')
.where({ id: 42 })
.update({ title: "The Hitchhiker's Guide to the Galaxy" }, ['id', 'title'])
transaction
是我之前创建的连接,所有更新后提交
这是最佳做法吗?
大规模会不会出问题?
I wondered if I can execute multiple update queries in parallel
没有。单个连接仅支持顺序执行查询。 node-postgres
不会阻止您一次发出多个调用,但它会在内部对它们进行排队,因此您不会从一次创建所有承诺并对其调用 Promise.all
中获得任何好处。
(也就是说,我不知道 Knex transaction
是如何工作的,如果它使用 connection pool 它实际上可能不会将您限制为单个连接。但是,如果您为多个 HTTP 客户端提供服务,那不是最佳做法,您应该只对每个 HTTP 请求使用连接。)
由于您正在使用事务,因此最佳做法是一个接一个地按顺序进行。
在您的情况下,如果其中一个查询失败,错误处理也非常令人讨厌,但 Promise.all()
可能会继续向已经回滚的事务发送查询。