@Autowired
private RedisTemplate redisTemplate;
@Test
public void execute() throws Exception {
String key = "HRPM_TTWYPTEST20210830";
unlock(new RedisLockEntity(key, key));
testlock(key, 2);
testlock(key, 1);
System.in.read();
}
private void testlock(String key, int mil) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
try {
if (lock(new RedisLockEntity(key, key))) {
System.out.println("进入锁" + mil);
Thread.sleep(mil * 1000);
}
unlock(new RedisLockEntity(key, key));
System.out.println("解除锁" + mil);
} catch (Exception ex) {
System.out.println("异常锁" + mil);
unlock(new RedisLockEntity(key, key));
System.out.println(ex.getMessage());
}
} catch (Exception e) {
}
}
});
thread1.start();
}
/**
* 加锁,自旋重试三次
*
* @param redisLockEntity 锁实体
* @return
*/
public boolean lock(RedisLockEntity redisLockEntity) {
boolean locked = false;
int tryCount = 50;
while (!locked && tryCount > 0) {
locked = redisTemplate.opsForValue().setIfAbsent(redisLockEntity.getLockKey(), redisLockEntity.getRequestId(), 2, TimeUnit.MINUTES);
tryCount--;
try {
if (!locked) {
Thread.sleep(200);
}
} catch (InterruptedException e) {
System.out.println("线程被中断" + Thread.currentThread().getId() + e.getMessage());
}
}
System.out.println("获得锁");
return locked;
}
/**
* 非原子解锁,可能解别人锁,不安全
*
* @param redisLockEntity
* @return
*/
public boolean unlock(RedisLockEntity redisLockEntity) {
if (redisLockEntity == null || StringUtil.isEmpty(redisLockEntity.getLockKey()))
return false;
boolean releaseLock = redisTemplate.delete(redisLockEntity.getLockKey());
return releaseLock;
}
基于RedisTemplate的分布式锁
最新推荐文章于 2024-06-02 07:06:13 发布