redis setIfAbsent和setnx的區別與使用說明

這篇文章主要介紹了redis setIfAbsent和setnx的區別與使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

redis setIfAbsent和setnx的區別與使用

如果為空就set值,并返回1文章源自四五設計網-http://www.wasochina.com/44694.html

如果存在(不為空)不進行操作,并返回0文章源自四五設計網-http://www.wasochina.com/44694.html

setIfAbsent 和 setnx 使用范圍

setIfAbsent 是java中的方法文章源自四五設計網-http://www.wasochina.com/44694.html

setnx 是 redis命令中的方法文章源自四五設計網-http://www.wasochina.com/44694.html

setnx 例子

1
2
3
4
5
6
redis> SETNX testkey "test"
(integer) 1
redis> SETNX testkey "test"
(integer) 0
redis> GET testkey
"test"

setIfAbsent 例子

1
2
3
4
5
6
redis> SETNX testkey "test"
(integer) 1
redis> SETNX testkey "test"
(integer) 0
redis> GET testkey
"test"

RedisTemplate 實現 setnx exptime (擴展 redisTemplate.setIfAbsent)

之前用 redisTemplate 實現setnx exptime 時 是分兩步的

1. redisTemplate.setIfAbsent文章源自四五設計網-http://www.wasochina.com/44694.html

2. redisTemplate.expire文章源自四五設計網-http://www.wasochina.com/44694.html

這樣的不是原子性的 可能在第一步與第二步之間 重新發布了或者服務器重啟了 這個key就永遠不會消失了文章源自四五設計網-http://www.wasochina.com/44694.html

可以采用以下的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static boolean setIfAbsent(final String key, final Serializable value, final long exptime) {
????Boolean b = (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
????????@Override
????????public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
????????????RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
????????????RedisSerializer keySerializer = redisTemplate.getKeySerializer();
????????????Object obj = connection.execute("set", keySerializer.serialize(key),
????????????????????????????????valueSerializer.serialize(value),
????????????????????????????????SafeEncoder.encode("NX"),
????????????????????????????????SafeEncoder.encode("EX"),
????????????????????????????????Protocol.toByteArray(exptime));
????????????return obj != null;
????????}
????});
????return b;
}

以上為個人經驗,希望能給大家一個參考文章源自四五設計網-http://www.wasochina.com/44694.html 文章源自四五設計網-http://www.wasochina.com/44694.html

繼續閱讀
我的微信
微信掃一掃
weinxin
我的微信
惠生活福利社
微信掃一掃
weinxin
我的公眾號
 
  • 本文由 四五設計網小助手 發表于 2024年4月6日09:42:04
  • 轉載請務必保留本文鏈接:http://www.wasochina.com/44694.html

發表評論

匿名網友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖動滑塊以完成驗證