package com.ruoyi.web.tool;
|
|
import org.springframework.data.redis.core.RedisTemplate;
|
|
import java.util.UUID;
|
import java.util.concurrent.TimeUnit;
|
|
/**
|
* @author zhibing.pu
|
* @Date 2024/9/26 18:43
|
*/
|
public class RedisLock {
|
private RedisTemplate redisTemplate;
|
private String lockKey;
|
private int expireTime; // 锁的超时时间
|
private int timeout; // 获取锁的超时时间
|
|
|
public RedisLock(RedisTemplate redisTemplate, String lockKey, int expireTime, int timeout) {
|
this.redisTemplate = redisTemplate;
|
this.lockKey = lockKey;
|
this.expireTime = expireTime;
|
this.timeout = timeout;
|
}
|
|
public boolean lock() {
|
String identifier = UUID.randomUUID().toString();
|
long end = System.currentTimeMillis() + timeout;
|
while (System.currentTimeMillis() < end) {
|
if (redisTemplate.opsForValue().setIfAbsent(lockKey, identifier, expireTime, TimeUnit.SECONDS)) {
|
return true;
|
}
|
// 可以使用延时来减少CPU占用
|
try {
|
Thread.sleep(100);
|
} catch (InterruptedException e) {
|
Thread.currentThread().interrupt();
|
}
|
}
|
return false;
|
}
|
|
public void unlock() {
|
redisTemplate.delete(lockKey);
|
}
|
}
|