加锁
//uuid标识锁,防止删除其他线程的锁 String uuid = UUID.randomUUID().toString(); redisTemplate.opsForValue().setIfAbsent("lock",uuid,2, TimeUnit.SECONDS);
释放锁
//lua脚本,保证删除的原子性 String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; // 设置lua脚本返回的数据类型 DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); // 设置lua脚本返回类型为Long redisScript.setResultType(Long.class); redisScript.setScriptText(script); redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);