DistributedLock.java 1.9 KB
Newer Older
1 2
package com.central.common.lock;

3 4
import java.util.concurrent.TimeUnit;

5 6 7 8 9
/**
 * 分布式锁顶级接口
 *
 * @author zlt
 * @date 2018/5/29 14:12
10 11 12
 * <p>
 * Blog: https://zlt2000.gitee.io
 * Github: https://github.com/zlt2000
13 14 15
 */
public interface DistributedLock {
    /**
16 17 18 19 20 21 22
     * 获取锁,如果获取不成功则一直等待直到lock被获取
     * @param key 锁的key
     * @param leaseTime 加锁的时间,超过这个时间后锁便自动解锁;
     *                  如果leaseTime为-1,则保持锁定直到显式解锁
     * @param unit {@code leaseTime} 参数的时间单位
     * @param isFair 是否公平锁
     * @return 锁对象
23
     */
24 25 26 27
    Object lock(String key, long leaseTime, TimeUnit unit, boolean isFair) throws Exception;
    Object lock(String key, long leaseTime, TimeUnit unit) throws Exception;
    Object lock(String key, boolean isFair) throws Exception;
    Object lock(String key) throws Exception;
28 29

    /**
30 31
     * 尝试获取锁,如果锁不可用则等待最多waitTime时间后放弃
     * @param key 锁的key
zlt2000's avatar
zlt2000 已提交
32
     * @param waitTime 获取锁的最大尝试时间(单位 {@code unit})
33 34 35 36
     * @param leaseTime 加锁的时间,超过这个时间后锁便自动解锁;
     *                  如果leaseTime为-1,则保持锁定直到显式解锁
     * @param unit {@code waitTime} 和 {@code leaseTime} 参数的时间单位
     * @return 锁对象,如果获取锁失败则为null
37
     */
38 39 40 41
    Object tryLock(String key, long waitTime, long leaseTime, TimeUnit unit, boolean isFair) throws Exception;
    Object tryLock(String key, long waitTime, long leaseTime, TimeUnit unit) throws Exception;
    Object tryLock(String key, long waitTime, TimeUnit unit, boolean isFair) throws Exception;
    Object tryLock(String key, long waitTime, TimeUnit unit) throws Exception;
42 43 44

    /**
     * 释放锁
45
     * @param lock 锁对象
46
     */
47
    void unlock(Object lock) throws Exception;
48
}