如果为空就set值,并返回1
如果存在(不为空)不进行操作,并返回0
很明显,比get和set要好。因为先判断get,再set的用法,有可能会重复set值。
setIfAbsent 和 setnx
setIfAbsent 是java中的方法
setnx 是 redis命令中的方法
setnx 例子
redis> SETNX mykey "Hello"
(integer) 1
redis> SETNX mykey "World"
(integer) 0
redis> GET mykey
"Hello"
setIfAbsent 例子
代码:
BoundValueOperations boundValueOperations = this.redisTemplate.boundValueOps(redisKey);
flag = boundValueOperations.setIfAbsent(value); // flag 表示的是否set
boundValueOperations.expire(seconds, TimeUnit.SECONDS);
if(!flag){ // 重复
repeatSerial.add(serialNo);
continue;
}else{// 没有重复
norepeatSerial.add(serialNo);
}
本文介绍了Java中的`setIfAbsent`方法和Redis命令`setnx`,这两种条件设置操作用于避免重复设置值。通过示例展示了如何使用这两个功能,当键值不存在时设置并返回1,若已存在则不操作并返回0。这种做法避免了不必要的重复设置,提高了代码效率。
2846

被折叠的 条评论
为什么被折叠?



