|
6 | 6 | import org.springframework.beans.factory.annotation.Autowired; |
7 | 7 | import org.springframework.data.redis.core.StringRedisTemplate; |
8 | 8 | import org.springframework.data.redis.core.ValueOperations; |
| 9 | +import org.springframework.data.redis.core.script.DefaultRedisScript; |
9 | 10 | import org.springframework.stereotype.Service; |
10 | 11 |
|
| 12 | +import java.util.Arrays; |
11 | 13 | import java.util.List; |
12 | 14 | import java.util.Map; |
| 15 | +import java.util.UUID; |
13 | 16 | import java.util.concurrent.TimeUnit; |
14 | 17 |
|
15 | 18 | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; |
@@ -99,17 +102,26 @@ private List<TypeEntity> getDataFromDB() { |
99 | 102 |
|
100 | 103 | @Override |
101 | 104 | public List<TypeEntity> getTypeEntityListByRedisDistributedLock() throws InterruptedException { |
102 | | - // 1.先抢占锁 |
103 | | - Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "123"); |
| 105 | + // 1.生成唯一 id |
| 106 | + String uuid = UUID.randomUUID().toString(); |
| 107 | + // 2. 抢占锁 |
| 108 | + Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 10, TimeUnit.SECONDS); |
104 | 109 | if(lock) { |
105 | | - // 2.抢占成功,执行业务 |
| 110 | + System.out.println("抢占成功:" + uuid); |
| 111 | + // 3.抢占成功,执行业务 |
106 | 112 | List<TypeEntity> typeEntityListFromDb = getDataFromDB(); |
107 | | - // 3.解锁 |
108 | | - redisTemplate.delete("lock"); |
| 113 | + |
| 114 | + // 4.Lua 脚本解锁 |
| 115 | + String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end"; |
| 116 | + redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid); |
| 117 | + |
| 118 | + System.out.println("解锁成功:" + uuid); |
| 119 | + |
109 | 120 | return typeEntityListFromDb; |
110 | 121 | } else { |
| 122 | + System.out.println("抢占失败,等待锁释放"); |
111 | 123 | // 4.休眠一段时间 |
112 | | - //sleep(100); |
| 124 | + sleep(100); |
113 | 125 | // 5.抢占失败,等待锁释放 |
114 | 126 | return getTypeEntityListByRedisDistributedLock(); |
115 | 127 | } |
|
0 commit comments