How to create a distributed lock with Redis?

前端 未结 5 1233
广开言路
广开言路 2020-12-28 17:37

On the redis documentation, I found a primitive lock can be implemented via SETNX:

http://redis.io/commands/setnx

  • C4 sends SETNX lo

5条回答
  •  情话喂你
    2020-12-28 18:44

    I gem'ed out the SET EX NX solution that misterion mentioned to a cool gem - simple_redis_lock

    The code is simple and looks like this:

    def lock(key, timeout)
      if @redis.set(key, Time.now, nx: true, px: timeout)
        begin
          yield
        ensure
          release key
        end
      end
    end
    

提交回复
热议问题