package com.qiaoba.module.demo.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.module.demo.service.DemoLock4jService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Demo-Lock4j 业务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022-09-22 04:20:28
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DemoLock4jServiceImpl implements DemoLock4jService {

    private final LockTemplate lockTemplate;

    @Override
    public void apiLock() {
        //... 各种不需要上锁的操作
        String lockKey = "lock4j:apiLock";
        // expire = -1 锁自动续期
        final LockInfo lockInfo = lockTemplate.lock(lockKey, -1, 1000);
        //申请锁失败
        if (null == lockInfo) {
            throw new ServiceException("业务处理中，请稍后再试...");
        }
        //申请锁成功
        try {
            ThreadUtil.sleep(30 * 1000);
            log.info("执行完毕 apiLock, 当前线程{}", Thread.currentThread().getName());
        } finally {
            lockTemplate.releaseLock(lockInfo);
        }
    }

    @Override
    public void annotationLock() {
        // 休眠 10s
        ThreadUtil.sleep(10 * 1000);
        log.info("执行完毕 annotationLock, 当前线程{}", Thread.currentThread().getName());
    }
}
