| | |
| | | } |
| | | |
| | | /** |
| | | * 尝试加锁 |
| | | * |
| | | * @param lockKey 锁的key |
| | | * @param requestId 锁的持有者标识符(如UUID) |
| | | * @param expireTime 锁的过期时间(秒) |
| | | * @return 加锁成功返回true,否则返回false |
| | | */ |
| | | public boolean trylockLoop(String lockKey, String requestId,long expireTime) { |
| | | String lockKeyWithPrefix = LOCK_PREFIX + lockKey; |
| | | // 使用SET命令的NX和PX选项来加锁 |
| | | Boolean result = false; |
| | | int num = 50; |
| | | while (num>0){ |
| | | result = redisTemplate.opsForValue().setIfAbsent(lockKeyWithPrefix, requestId, expireTime, TimeUnit.SECONDS); |
| | | if (result){ |
| | | break; |
| | | } |
| | | try { |
| | | TimeUnit.MILLISECONDS.sleep(200); |
| | | } catch (InterruptedException e) { |
| | | throw new RuntimeException(e); |
| | | } |
| | | num--; |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 解锁 |
| | | * |
| | | * @param lockKey 锁的key |