| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | @Autowiredprivate RedisTemplate redisTemplate;
 
 @RequestMapping("/test")
 public void test() {
 
 
 String uuid = UUID.randomUUID().toString();
 while (!redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS)) {
 try {
 Thread.sleep(2000);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 
 try {
 System.out.println(Thread.currentThread() + " -- 获取锁成功,执行业务...");
 Thread.sleep(5000);
 } catch (Exception 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";
 redisTemplate.execute(new DefaultRedisScript(script, Long.class), Arrays.asList("lock"), uuid);
 System.out.println(Thread.currentThread() + " -- 释放锁");
 }
 }
 
 |