RedisTemplate opsForValue()的 setIfAbsent() 和 getAndSet()

setIfAbsent( key, value)

1.如果键不存在则新增,存在则不改变已经有的值。

2.存在返回 false,不存在返回 true。

3.boolean lock = redisTemplate.opsForValue().setIfAbsent("testKey","123");

一开始是不存在key “testKey” 的,所以lock 为 true;但是后面创建并添加了值“123”。

redisTemplate.opsForValue().get("testKey");

是有值的,为“123”。

lock = redisTemplate.opsForValue().setIfAbsent("testKey","321");

已存在key “testKey”,所以无法赋值,lock 为 false;

redisTemplate.opsForValue().get("testKey");

值没变,还是“123”。

getAndSet()

1.Object redisKey = redisTemplate.opsForValue().getAndSet("testKey", "000");

获取原来key键对应的值并重新赋新值。

2.System.out.println(redisKey);

redisKey为变之前的值,“123”。

3.System.out.println(redisTemplate.opsForValue().get("testKey"));

为改变后的值,“000”

经验分享 程序员 微信小程序 职场和发展