wang-hao-jie
2021-10-19 e48043a2df9ca0c73fe18298bab3c4d42ca5c0c7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package cn.exrick.xboot.core.common.lock;
 
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.concurrent.TimeUnit;
 
 
/**
 * @author Exrick
 */
@Slf4j
@Component
public class RedisLockTemplate implements DistributedLockTemplate {
 
    @Autowired
    private RedissonClient redisson;
 
    @Override
    public Object execute(String lockId, Integer timeout, Integer leaseTime, TimeUnit unit, Callback callback) {
 
        if (timeout == null) {
            timeout = 0;
        }
        RLock lock = null;
        boolean getLock = false;
        try {
            lock = redisson.getLock(lockId);
            if (leaseTime == null || leaseTime <= 0) {
                getLock = lock.tryLock(timeout, unit);
            } else {
                getLock = lock.tryLock(timeout, leaseTime, unit);
            }
            if (getLock) {
                // 拿到锁
                return callback.onGetLock();
            } else {
                // 未拿到锁
                return callback.onTimeout();
            }
        } catch (InterruptedException ex) {
            log.error(ex.getMessage(), ex);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (getLock) {
                // 释放锁
                lock.unlock();
            }
        }
        return null;
    }
}