分布式锁

/**
     * 设置redis分布式锁
     *
     * @param keyType 分布式锁类型
     * @param hKey    分布式锁键值
     * @return 对象列表
     */
    public boolean getRedisTempLock(final String keyType, final String hKey, long tempValue) {
        String key = keyType.concat(hKey);
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, tempValue, 5, TimeUnit.MINUTES);
        return result != null && result;
    }
if (redisUtil.getRedisTempLock(OrderOutType.RECEIVING_GOODS.getType(), serviceNo,
                System.currentTimeMillis())) {
                log.info("Op:confirmReceiving, Locked:{} successfully.", serviceNo);
            } else {
                log.error("Op:confirmReceiving, Locked:{} fail!", serviceNo);
                return BaseExResponse.error(ErrorMsg.OPERATE_FAIL.getMsg());
            }
// roll back
        try {
            if (redisUtil.getRedisTempLock(OrderOutType.RECEIVING_GOODS.getType(), serviceNo,
                System.currentTimeMillis())) {
                log.info("Op:confirmReceiving, Locked:{} successfully.", serviceNo);
            } else {
                log.error("Op:confirmReceiving, Locked:{} fail!", serviceNo);
                return BaseExResponse.error(ErrorMsg.OPERATE_FAIL.getMsg());
            }
        } catch (Exception e) {
            log.error("Op:confirmReceiving, params:{} has error:", JSON.toJSONString(record), e);
            if (e instanceof BaseException) {
                throw new RuntimeException("次品收货失败:" + e.getMessage());
            }
            throw new RuntimeException("次品收货失败:请联系管理员处理");
        } finally {
            log.info("Op:confirmReceiving, Lock:{} released successfully", serviceNo);
            redisUtil.deleteRedisTempLock(OrderOutType.RECEIVING_GOODS.getType(), serviceNo);
        }

 

posted on 2024-07-01 18:08  IT-QI  阅读(2)  评论(0编辑  收藏  举报