How can I read from Redis inside a MULTI block in Ruby?

前端 未结 2 672
终归单人心
终归单人心 2021-02-08 10:07

I\'m encapsulating a complicated set of Redis commands in a MULTI transaction, but the logic in the transaction depends on values already in Redis. But all reads within a transa

2条回答
  •  生来不讨喜
    2021-02-08 10:27

    As Sergio states in his comment, you can't optionally execute a MULTI block like that in Redis. See the documentation on transactions:

    Either all of the commands or none are processed.

    You can, however, use WATCH to implement optimistic locking using check-and-set (pseudo code):

    SET foo bar
    WATCH foo
    $foo = GET foo
    MULTI
    if $foo == 'bar'
      SET foo baz
    EXEC
    GET foo
    

    Using WATCH, the transaction will only be executed if the watched key(s) has not been changed. If the watch key is changed, the EXEC will fail, and you can try again.

    Another possibility is using the scripting functionality, but that's only available in the 2.6 release candidate.

提交回复
热议问题