2

我想我可能遗漏了一些重要的东西,但是如何使用 Spring Data redis 对给定键进行原子递减?

RedisAtomicLongRedisAtomicInteger绑定到我们在实例化它们时指定的键。

我将如何对我选择的任何键进行原子减量?

我必须求助于多执行吗?在 vanilla redis 中,我可以通过简单的 DECR 命令自动递减任何键,而无需使用 multi exec。我在这里错过了什么吗?

谢谢,理查德。

4

1 回答 1

7

如果要通过动态键递减,可以执行以下操作

// 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();
}
于 2015-03-19T01:30:27.020 回答