/**
 * bobotuan.com Inc.
 * Copyright (c) 2004-2020 All Rights Reserved.
 */
package com.qs.mp.framework.service;


import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.utils.LogUtil;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;

/**
 * 业务锁操作抽象类
 *
 * @author chunping.zhongcp
 * @version $Id: AbstractBizLockService.java, v 0.1 2020/6/5 chunping.zhongcp Exp $
 */
public abstract class AbstractBizLockService<T> {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    public T processWithLock(String lockKey, RedisLockRegistry redisLockRegistry, Object... param) {
        //  加业务锁
        Lock lock = null;
        try {
            lock = redisLockRegistry.obtain(lockKey);
            if (!lock.tryLock(2, TimeUnit.SECONDS)) {
                LogUtil.warn(logger, "分布式锁获取超时，key:" + lockKey);
                throw new ServiceException("锁获取超时", ErrorCodeEnum.ERROR_CODE_1004.getCode());
            }

            return process(param);

        } catch (InterruptedException e){
            LogUtil.error(logger, "分布式锁获取异常，key:" + lockKey, e);
            throw new ServiceException("锁获取超时", ErrorCodeEnum.ERROR_CODE_1004.getCode());
        } finally {
            if (null != lock) {
                try {
                    lock.unlock();
                } catch (Exception e) {
                    LogUtil.error(logger, "分布式锁释放异常，key:" + lockKey, e);
                }
            }
        }
    }

    protected abstract T  process(Object... param);
}
