springboot-redis中setIfAbsent和setIfPresent区别
spring-data-redis2.3.1版本中:public Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit) {byte[] rawKey = this.rawKey(key);byte[] rawValue = this.rawValue(value);Expiration expiration = Expir
·
spring-data-redis2.3.1版本中:
public Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit) {
byte[] rawKey = this.rawKey(key);
byte[] rawValue = this.rawValue(value);
Expiration expiration = Expiration.from(timeout, unit);
return (Boolean)this.execute((connection) -> {
return connection.set(rawKey, rawValue, expiration, SetOption.ifAbsent());
}, true);
}
public Boolean setIfPresent(K key, V value, long timeout, TimeUnit unit) {
byte[] rawKey = this.rawKey(key);
byte[] rawValue = this.rawValue(value);
Expiration expiration = Expiration.from(timeout, unit);
return (Boolean)this.execute((connection) -> {
return connection.set(rawKey, rawValue, expiration, SetOption.ifPresent());
}, true);
}
跟代码后发现区别在于:
public static RedisStringCommands.SetOption ifPresent() {
return SET_IF_PRESENT;
}
public static RedisStringCommands.SetOption ifAbsent() {
return SET_IF_ABSENT;
}
查询spring官方文档得出结论:
SET_IF_ABSENT ----> NX
SET_IF_PRESENT ---->XX
NX – Only set the key if it does not already exist.
XX – Only set the key if it already exist.
--NX命令: 仅当key不存在时,set才会生效。例如
127.0.0.1:6379> set hello world
OK
127.0.0.1:6379> set hello newval nx # 由于hello存在,所以set命令不会生效,返回nil表示失败。
(nil)
127.0.0.1:6379> get hello # 此时还是原来的值。
"world"
127.0.0.1:6379> set newkey value nx # newkey不存在,set命令成功。
OK
127.0.0.1:6379> get newkey
"value"
---XX命令:仅当key存在时,set才会生效。 例如:
127.0.0.1:6379> set hello world
OK
127.0.0.1:6379> set hello newval xx # 由于hello存在,所以set命令会设置成功。
OK
127.0.0.1:6379> get hello # 可以获取到新值
"newval"
127.0.0.1:6379> set newkey val xx # 由于newkey不存在,所以不会设置成功
(nil)
127.0.0.1:6379> get newkey
(nil)
更多推荐
已为社区贡献1条内容
所有评论(0)