1、setNX命令说明:
SET resource_name my_random_value NX PX 30000
2、代码演示:
@Service
public class BaseSetNXDistributeLockService {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseSetNXDistributeLockService.class);
@Autowired
private RedisTemplate redisTemplate;
public String redisLock() {
LOGGER.info("我进入了方法!");
String key = "redisKey";
String value = UUID.randomUUID().toString();
RedisCallback<Boolean> redisCallback = connection -> {
RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
Expiration expiration = Expiration.seconds(30);
byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
byte[] redisValue = redisTemplate.getValueSerializer().serialize(value);
Boolean result = connection.set(redisKey, redisValue, expiration, setOption);
return result;
};
Boolean lock = (Boolean) redisTemplate.execute(redisCallback);
if (lock) {
LOGGER.info("我进入了锁!");
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n"+
" return redis.call(\"del\",KEYS[1])\n"+
"else\n"+
" return 0\n"+
"end";
RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);
List<String> keys = Arrays.asList(key);
Boolean result = (Boolean) redisTemplate.execute(redisScript,keys,value);
LOGGER.info("释放锁的结果:"+result);
}
}
return "方法执行完成!";
}
}
|