分布式锁工具类
import com.cesec.common.enums.ResultEnum;
import com.cesec.common.exception.BizException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class DistributeLockUtils {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public boolean lock(String lockKey, String lockKeyId, long timeout){
return stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockKeyId, timeout, TimeUnit.SECONDS);
}
public boolean unLock(String lockKey, String lockKeyId) {
if (lockKeyId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
Boolean deleteFlag = stringRedisTemplate.delete(lockKey);
System.out.println("锁释放成功标志 " + " [" + Thread.currentThread().getName() + "]");
return deleteFlag;
}
return false;
}
public void checkLock(boolean flag) {
CheckUtils.checkArgument(flag, ResultEnum.SYSTEM_BUSY);
}
@Async("taskExecutor")
public void extendExpTime(String lockKey, final long timeout) {
try {
while (true) {
stringRedisTemplate.expire(lockKey, timeout, TimeUnit.SECONDS);
System.out.println("锁延长:" + timeout + "s [" + Thread.currentThread().getName() + "]");
String lockKeyId = stringRedisTemplate.opsForValue().get(lockKey);
if (StringUtils.isEmpty(lockKeyId)) {
return;
}
long timeInterval = timeout / 3 == 0 ? 1 : timeout / 3;
Thread.sleep(timeInterval * 1000);
}
} catch (Exception e) {
throw new BizException(ResultEnum.SYSTEM_ERROR);
}
}
}
springboot 分布式锁的实现代码
String lockKeyId = UUID.randomUUID().toString();
long timeout = 5L;
boolean flag = distributeLockUtils.lock(productId, lockKeyId, timeout);
distributeLockUtils.extendExpTime(productId, timeout);
distributeLockUtils.checkLock(flag);
System.out.println("request start " + "[" + Thread.currentThread().getName() + "]");
try {
**************************
**************************
**************************
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("request end" + " [" + Thread.currentThread().getName() + "]");
} finally {
distributeLockUtils.unLock(productId, lockKeyId);
}