方式一 RLock lock = redissonClient.getLock("Export:create:" + Context.get().getCorpId()); try { if (lock.tryLock(5, 10, TimeUnit.SECONDS)) { //业务处理 } else { Assert.isTrue(false, "排队中,请稍后重试!"); } } catch (InterruptedException e) { Assert.isTrue(false, "请勿重复操作!"); } finally { if (lock.isLocked()) { lock.unlock(); } }
方式二: RLock lock = redisson.getLock(String.format(REWARD_CARD_LOCK_KEY, 2));
try {
//尝试加锁,最多等待10秒,上锁以后10秒自动解锁
if (lock.tryLock(10,10, TimeUnit.SECONDS)) {
try {
//处理
logger.info("tryLock thread---{}, lock:{}", Thread.currentThread().getId(), lock);
} catch (Exception e) {
} finally {
//解锁
lock.unlock();
}
}
} catch (InterruptedException e) {
//处理
//保留中断发生的证据,以便调用栈中更高层的代码能知道中断,并对中断作出响应
Thread.currentThread().interrupt();
}
|
public void testReentrantLock(RedissonClient redisson){ RLock lock = redisson.getLock("anyLock"); try{ // 1. 最常见的使用方法 //lock.lock(); // 2. 支持过期解锁功能,10秒钟以后自动解锁, 无需调用unlock方法手动解锁 //lock.lock(10, TimeUnit.SECONDS); // 3. 尝试加锁,最多等待3秒,上锁以后10秒自动解锁 boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS); if(res){ //成功 // do your business } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }
|
转载至:https://blog.csdn.net/l1028386804/article/details/73523810