web123456

Use of redis setIfAbsent

If empty, set the value and return 1
If there is (not empty), no operation is performed and return 0

Obviously, it's better than get and set. Because you first judge the use of get and then set, the set value may be repeated.

setIfAbsent and setnx

setIfAbsent is a method in java
setnx is a method in the redis command

setnx example
redis> SETNX mykey "Hello"
(integer) 1
redis> SETNX mykey "World"
(integer) 0
redis> GET mykey
"Hello"
setIfAbsent Example

Code:

BoundValueOperations boundValueOperations = this.redisTemplate.boundValueOps(redisKey);
flag = boundValueOperations.setIfAbsent(value); // flag indicates whether set
boundValueOperations.expire(seconds, TimeUnit.SECONDS);

if(!flag){ // repeat
    repeatSerial.add(serialNo);
    continue;
}else{// No duplication
    norepeatSerial.add(serialNo);
}