Search code examples
redisredisson

Redisson: Locking with Spring cache


Redisson provides support for locking backed by Redis. It also provides implementation for working with spring cache framework. But based on what I saw locking is not called by default when try to update a key in a cache using spring cache framework. Redisson has separate APIs for locking a particular key. Is that correct?

Also the locking APIs seem to take key as an input so I am not clear how locking works. For locking I am assuming you need both cache name and key.

I am new to redis so any help in throwing some light on this is really appreciated. Thanks


Solution

  • Firstly, locking in Redisson is implement by Redis, but not only used for Redis updating.

    For example if you want to implement an atomic operation like this:

    1. Get key value from Redis
    2. Calculate a new value based on some logic
    3. Save the new value to Redis and Mysql

    You can use Redisson lock to make the operation atomically.

    Secondly, in Redis, set/update command is atomic and you don't need to lock the key if you only update the value.

    And for locking API, Redisson implement lock by Redis key/value, so you only need to provide lock-key, which generally contains a resource id and resource type(like "lock:user:31352")