分布式锁之实战

分布式锁,主要 在分布式情况下,针对同一次业务请求,前端未做防重,后端短时间内接收多次相同的请求,锁 url;

方式一:

// org.apache.curator.framework.recipes.locks.InterProcessLock
// org.apache.curator.framework.recipes.locks.InterProcessMutex.InterProcessMutex(CuratorFramework, String)
​
public Result apply(@Validated RefundApplyDTO dto) {
    log.info("cashier refund apply:{}", JSON.toJSONString(dto));
    InterProcessLock lock = lock(dto);
    try {
        if (lock.acquire(1L, TimeUnit.SECONDS)) {
            // 业务逻辑代码
            ......
                
             return ResultUtils.successed("申请成功");
        }
    } catch (Exception e) {
        log.info("refund apply acquire lock failed", e);
    }finally {
        try {
            lock.release();
        } catch (Exception e) {
            log.info("lock release error", e);
        }
    }
    return ResultUtils.failed("系统忙");
}
​
@Autowired
private CuratorFramework curatorFramework; // org.apache.curator.framework.CuratorFramework
​
// 分布式锁 锁的路径:进行MD5加密,防止 业务参数过多,使用MD5加密,加密前,参数先排序;
private InterProcessLock lock(RefundApplyDTO dto) {
    List bills = dto.getRefundDetails().stream().map(d -> d.getBillCode()).collect(Collectors.toList());
    String sign = MD5Utils.sign(bills); // 加密前 最好 对 业务参数 排序,这样保证唯一
    return new InterProcessMutex(curatorFramework, "/cashier/refund/apply" + sign);

方式二:

// org.apache.curator.framework.recipes.locks.InterProcessMutex
// org.apache.curator.framework.CuratorFramework
​
@Autowired
private CuratorFramework curatorFramework;
​
public Result pay(CashPayRequest request) {
    log.info("pay:{}", JSON.toJSONString(request));
    InterProcessMutex mutex = new InterProcessMutex(curatorFramework, "/cashPay/pay/" + request.getBillCode());
    try {
        mutex.acquire();
        // 业务逻辑...
        
        return new Result<>(BaseConstants.SUCCESS, "xxx...成功", null, null, BaseConstants.SYS_SUCCESS);
    } catch (Exception e) {
        log.info("xxx...失败", e);
    } finally {
        try {
            mutex.release();
        } catch (Exception e) {
            log.error("xxx...锁释放异常", e);
        }
    }
    return new Result<>(BaseConstants.ERROR, "xxx...失败", null, null, BaseConstants.SYS_ERROR);
}

 

你可能感兴趣的:(分布式锁之实战)