kongdeqiang
2020-12-10 4104ec82c9799b592e03aa851086e802bbf6c98b
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
package cn.cetc54.platform.core.common.lock;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;
 
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
 
 
/**
 * @author Exrick
 */
@Slf4j
@Component
public class RedisLockTemplate implements DistributedLockTemplate {
 
    @Autowired
    private RedisLockRegistry redisLockRegistry;
 
    @Override
    public Object execute(String lockId, Integer timeout, TimeUnit unit, Callback callback) {
 
        Lock lock = null;
        boolean getLock = false;
        try {
            lock = redisLockRegistry.obtain(lockId);
            getLock = lock.tryLock(timeout, 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;
    }
}