业务场景:
比如:给某条记录点赞时, 有两个条件:(1)本条记录有点赞限制 (2) 点赞人有点赞限制。
问题: 并发时,需要加锁, 而且需要同时加两把锁。
工具类:
@Service
public class RedissonService{
@Autowired
private RedissonClient redissonClient;
public RedissonClient getRedissonClient() throws IOException {
return redissonClient;
}
/**
* 获取锁
*/
public RLock getRLock(String objectName) {
return redissonClient.getLock(objectName);
}
/**
* @desc : 同时加多个锁
**/
public RLock getMultiLock(RLock... locks){
return redissonClient.getMultiLock(locks);
}
}
业务逻辑:
// 加锁1
RLock lock1 = redissonService.getRLock("xxx1");
// 加锁2
RLock lock2 = redissonService.getRLock("xxx2");
RLock multiLock = redissonService.getMultiLock(lock1, lock2);
try {
boolean bs = multiLock.tryLock(2, 3, TimeUnit.SECONDS);
if (!bs) {
log.info("没有获取到分布式锁");
ApiResult.fail("并发错误,请重试");
}
// 业务逻辑
}catch (Exception ex){
log.error("异常,{}", ex);
return ApiResult.fail("请求异常");
}finally {
if(multiLock.isHeldByCurrentThread()) {
multiLock.unlock();
}
}
}
参考:https://www.modb.pro/db/193555
https://baijiahao.baidu.com/s?id=1736377262695968742&wfr=spider&for=pc