redis setIfAbsent和setnx的區(qū)別與使用說明

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

redis setIfAbsent和setnx的區(qū)別與使用

如果為空就set值,并返回1文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.html

如果存在(不為空)不進(jìn)行操作,并返回0文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.html

setIfAbsent 和 setnx 使用范圍

setIfAbsent 是java中的方法文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.html

setnx 是 redis命令中的方法文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.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 實(shí)現(xiàn) setnx exptime (擴(kuò)展 redisTemplate.setIfAbsent)

之前用 redisTemplate 實(shí)現(xiàn)setnx exptime 時(shí) 是分兩步的

1. redisTemplate.setIfAbsent文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.html

2. redisTemplate.expire文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.html

這樣的不是原子性的 可能在第一步與第二步之間 重新發(fā)布了或者服務(wù)器重啟了 這個(gè)key就永遠(yuǎn)不會(huì)消失了文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.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;
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.html 文章源自四五設(shè)計(jì)網(wǎng)-http://www.wasochina.com/44847.html

繼續(xù)閱讀
我的微信
微信掃一掃
weinxin
我的微信
惠生活福利社
微信掃一掃
weinxin
我的公眾號(hào)
 

發(fā)表評(píng)論

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

拖動(dòng)滑塊以完成驗(yàn)證