Redis存储(或任何数据库?)锁机制(NodeJS)

时间:2021-06-24 16:52:30

I have the following problem: I'm using Redis with NodeJS together via mranney's driver and my NodeJS webserver is retrieving some data from Redis, doing some operations on it and saving it back to the Redis. But this operation (call it X) may take a while so multiple users can fire it at the same time on the same resources.

我有以下问题:我通过mranney的驱动程序将Redis与NodeJS一起使用,我的NodeJS网络服务器正在从Redis中检索一些数据,对其进行一些操作并将其保存回Redis。但是这个操作(称之为X)可能需要一段时间,因此多个用户可以在同一资源上同时触发它。

So if a user A fires X and user B fires X at the same time I want user A to finish the job and then user B to get the (processed) data and do X. In the meantime user B waits. The order of users is irrelevant - only that one-at-a-time. So how to achieve this in my scenario? How to lock/unlock Redis? Is it even possible?

因此,如果用户A触发X并且用户B同时触发X,我希望用户A完成作业,然后用户B获取(已处理)数据并执行X.同时用户B等待。用户的顺序无关紧要 - 只是一次一个。那么如何在我的场景中实现这一目标呢?如何锁定/解锁Redis?它甚至可能吗?

1 个解决方案

#1


6  

There are a few ways to implement locking in Redis, without knowing more about scenario it sounds like SETNX would work. See Design pattern: Locking with SETNX in the Redis documentation. Also, transactions in Redis might be interesting reading, although I suspect it's not exactly what you're after in this case.

有几种方法可以在Redis中实现锁定,而不需要了解更多关于场景的信息,这听起来像SETNX会起作用。请参阅Redis文档中的设计模式:使用SETNX锁定。此外,Redis中的交易可能是有趣的阅读,虽然我怀疑它并不完全是你在这种情况下所追求的。

#1


6  

There are a few ways to implement locking in Redis, without knowing more about scenario it sounds like SETNX would work. See Design pattern: Locking with SETNX in the Redis documentation. Also, transactions in Redis might be interesting reading, although I suspect it's not exactly what you're after in this case.

有几种方法可以在Redis中实现锁定,而不需要了解更多关于场景的信息,这听起来像SETNX会起作用。请参阅Redis文档中的设计模式:使用SETNX锁定。此外,Redis中的交易可能是有趣的阅读,虽然我怀疑它并不完全是你在这种情况下所追求的。