场景
当我们新建一个课程时,课程名在创建、更新时可能会导致重复,这就使用锁来解决
一、代码
//新建一个方法verifyDuplicateName
//dtoList就是先去查询数据有无名字为name的课程,但是我们做的是分布式,就需要用到锁来控制
private String verifyDuplicateName(PrivateCurriculumDTO dto, List<PrivateCurriculumDTO> dtoList)(
String key = null;
try{
if (CollectionUtils,isEmpty(dtoList)) {
key = dto.getEnterpriseld)+ "+ dto.getName();
RLock lock = redissonClient.getLock(key);
if (lock.isLocked()){
throw new BusinessException("改课程名称已存在",60001);
}
boolean b = false;
try{
b = lock.tryLock(CurriculumConstant.TRY TIMEOUT, CurriculumConstant.LOCK EXPIRE, TimeUnit.MILLISECONDS);
}catch(InterruptedException ){
log.info("尝试获取锁失败",e);
if (lock.isLocked()){
throw new BusinessException("改课程名称已存在",60001);
}
//抛异常出来
}
}
}
if (CollectionUtils,isEmpty(dtoList)) (
key = dto.getEnterpriseld()+ "+ dto.getName();
RLock lock = redissonClient.getLock(key);
if (lock.isLocked()) {
throw new BusinessException("该课程名称已存在”,60001);}
boolean b = false;
try (
b = lock.tryLock(CurriculumConstant.TRY TIMEOUT, CurriculumConstant.LOCK EXPIRE, TimeUnit.MILLISECONDS);
) catch (InterruptedException e)(
log.info("尝试获取锁失败",e);
if (lock.isLocked)) (
lock,unlock();
throw new RuntimeException(e);
if (!b) {
throw new BusinessExceptionC"该课程名称已存在",60001);
}
else {
throw new BusinessException("该课程名称已存在",60001);}
return key;
) catch (Exception ex){
doUnLock(key);
throw ex;
}
}
总结
上面是针对分布式的重复名称的判断,如果只是单单传入list集合判断重复,可以用我下面的流集合判断
List<String> names =
names.stream.collect(Collectors.groupingBy(e->e,Collectors.counting())).entrySet().stream().filter(item.item.getValue() >1)