Search code examples
javaspringspring-data-redis

Spring data redis atomic integer variable key name


I think I'm probably missing something big, but how do you do an atomic decrement on a given key using Spring Data redis?

The RedisAtomicLong and RedisAtomicInteger are bound to the key we specify while instantiating them.

How would I do an atomic decrement on any key of my choice?

Do I have to resort to multi-exec? In vanilla redis, i can atomically decrement any key without resorting to multi exec, by simple using the DECR command. Am I missing something here?

Thanks, Richard.


Solution

  • If you want to decrement by dynamic keys you can do the following

    // inject the actual template
    @Autowired
    private RedisTemplate<String, Integer> template; // This can be RedisTemplate<String, Long> also based on your need
    
    // inject the template as ValueOperations
    @Resource(name="redisTemplate")
    private ValueOperations<String, Integer> valueOps;
    
    public Integer decrement(String key) {
        return ((Long)valueOps.increment(key, -1l)).intValue();
    }