RLock lock = redissonClient.getLock(lockName);
RLock lock = redissonClient.getFairLock(lockName);
try {
//尝试加锁,最多等待7秒,上锁以后5秒自动解锁
res = lock.tryLock(7, 5, TimeUnit.SECONDS);
if(res) {
}
} catch (Exception e) {
}finally {
if(res) {
lock.unlock();
}
}
测试
@Test
public void testLock() {
final String lockKey = "test:lock";
for (int i = 0; i < 10; i++) {
final int b = i;
RBlockingQueue<String> blockingQueue = SKBeanUtils.getRedisService().getBlockingQueue("queue:name");
Thread a = new Thread(new Runnable() {
@Override
public void run() {
RLock lock = SKBeanUtils.getRedisService().getFairLock(lockKey);
boolean res=false;
try {
res = lock.tryLock(10, 5, TimeUnit.SECONDS);
if(res) {
System.out.println(System.currentTimeMillis());
String c = blockingQueue.poll(4, TimeUnit.SECONDS);
System.out.println(b+"获取到了"+c);
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
if(res) {
System.out.println(b+"处理完解锁");
lock.unlock();
}else {
System.out.println(b+"没有等到锁");
}
}
}
});
a.start();
}
}