@RestController
public class RedisLock {
@Resource
RedisTemplate<String, Object> redisTemplate;
@GetMapping("lock/{key}/{value}")
public String testLock(@PathVariable String key, @PathVariable String value) {
// 根据key获取分布式锁,并且设置过期时间
Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, value, 10, TimeUnit.SECONDS);
if (aBoolean) {
try {
System.out.println("获取到锁");
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Boolean unlock = unlockLua(key, value);
System.out.println(unlock);
}
} else {
System.out.println("未获取到锁");
}
return "测试锁";
}
public boolean unlockLua(String key, String value) {
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//用于解锁的lua脚本位置
redisScript.setLocation(new ClassPathResource("unlock.lua"));
redisScript.setResultType(Long.class);
//没有指定序列化方式,默认使用上面配置的
Object result = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
assert result != null;
return result.equals(1L);
}
// 在resources中创建 unlock.lua 加入以下代码
if redis.call('get',KEYS[1]) == ARGV[1] then
return redis.call('del',KEYS[1])
else
return 0
end
}