gpt4 book ai didi

Node.js avoid db race condition with cluster/pm2(Node.js避免了与群集/PM2的数据库争用条件)

转载 作者:bug小助手 更新时间:2023-10-25 18:46:38 27 4
gpt4 key购买 nike



I have a Node application which runs in cluster mode with pm2.

我有一个Node应用程序,它在PM2的集群模式下运行。



I also have a function which checks if a specific row is in a db table. If the row is missing it creates the row otherwise a value is set and saved.

我还有一个检查特定行是否在数据库表中的函数。如果该行丢失,则创建该行,否则设置并保存一个值。



I only need one row for each combination of userId and groupId.

我只需要为UserID和groupID的每个组合占一行。



function someFunction()={
return Activation.findOne({ where: { userId: userId, groupId: groupId } })
.then(activationObject => {
if (!activationObject) {
return Activation.create({ userId: userId, groupId: groupId, activationTime: sequelize.fn('NOW') })
} else {
activationObject.activationTime = sequelize.fn('NOW');
return activationObject.save()
}
})
}


How can I avoid race conditions when running node in cluster mode?
Currently if first worker checks the row is available and the second checks at the same time both get no result and in the end we have two newly created rows instead of one.

如何避免在群集模式下运行节点时出现争用情况?目前,如果第一个Worker检查行可用,同时第二个检查都不会得到任何结果,最后我们有两个新创建的行,而不是一个。



I know that Sequelize provides a findOrCreate() method but I wanted an easy understandable example.

我知道Sequelize提供了findOrCreate()方法,但我想要一个简单易懂的示例。


更多回答
优秀答案推荐

The easiest way would be to add a UNIQUE constraint for the combination of userId and groupId with an ON CONFLICT REPLACE clause, and always create a new row instead of updating. This will cause a newly inserted row with the new activationTime to replace the old row.

最简单的方法是使用ON CONFICT REPLACE子句为用户ID和组ID的组合添加唯一约束,并始终创建新行而不是更新。这将导致新插入的行用新的激活时间替换旧行。



You can additionally check the number of rows inserted to tell whether the insert succeeded or not.

您还可以检查插入的行数,以判断插入是否成功。



Example: UNIQUE (userId, groupId) ON CONFLICT REPLACE

示例:冲突替换上的唯一(UserID,groupID)



I'm late to the party, but if you have more complicated things to check in your first query, using a transaction with the appropriate isolation level can be helpful

我参加聚会已经晚了,但是如果您要在第一个查询中签入更复杂的内容,那么使用具有适当隔离级别的事务可能会很有帮助


This answer gives a nice example: TypeORM Database Lock: Please explain how to use database lock in TypeORM using setLock() function

这个答案给出了一个很好的例子:TypeORM数据库锁:请解释如何使用Setlock()函数在TypeORM中使用数据库锁


更多回答

This is a good solution to the problem. But isn't there anything like shared mutex or semaphores in node js?

这是解决这个问题的好办法。但是,在节点js中没有类似共享互斥体或信号量的东西吗?

Take a look at npmjs.com/browse/keyword/mutex and npmjs.com/browse/keyword/semaphore .

查看npmjs.com/Browse/Keyword/mutex和npmjs.com/Browse/Keyword/信号灯。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com