在node.js中实现互斥 [英] implement mutex in node.js

查看:140
本文介绍了在node.js中实现互斥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的node.js应用程序中实现互斥锁,这是Wiki http:中的互斥锁: //en.wikipedia.org/wiki/Mutual_exclusion .

I would like to implement a mutex inside my node.js application, here is the mutex in wiki http://en.wikipedia.org/wiki/Mutual_exclusion.

有没有准备好该主题的模块?如果没有,有什么想法可以帮助我实施它吗?

Is there any ready module for this topic? if not, any idea can help me to implement it?

推荐答案

有很多方法可以实现此目的.有两种简单的方法是通过Redis或Zookeeper服务器. Node.js的两个模块都有很好的模块.

There are many ways to accomplish this. Two easy ways are via Redis or Zookeeper servers. Node.js has very good modules for both of them.

在Redis中,您可以使用观看 + 命令来实现锁定.在Zookeeper中,您可以创建临时节点.两种方式都不会同时执行关键操作.

In Redis you can use WATCH + MULTI commands to implement locking. In Zookeeper you can create ephemeral nodes. In both way no two processes will execute the critical operation at the same time.

我最近在 node-ratelimiter 模块中实现了Redis方法,这是该模块的关键部分我们需要确保没有两个流程在Redis中增加相同值的生产应用程序.请参考观看

I have recently implemented Redis approach in a node-ratelimiter module which is a critical part of our production applications where we need to guarantee no two processes increment the same value in Redis. Refer to WATCH and MULTI for details. The code is in fact very easy to understand and read.

以Zookeeper为例,请参阅锁定配方.可以使用Zookeeper临时节点为分布式锁实现更为复杂的逻辑. Redis解决方案只是一个特例,如果您只需要Redis解决方案,它就可以很好地发挥作用.

For Zookeeper example, refer to Locks Recipe. It is possible to implement much more complex logic for distributed locks with Zookeeper ephemeral nodes. Redis solution is just a special case and works very well if you don't need more than that.

使用这两种方法,您可以为任何应用程序和任何逻辑实现互斥体.

Using these two approaches you can implement mutexes for any app and any logic.

这篇关于在node.js中实现互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆