Java分布式锁--Redis实现

2020-09-14  本文已影响0人  千年的心

分布式并发环境下,为了保证事务操作的原子性,需要引入分布式锁来保证一连串行为是原子性操作,在此简单的实现锁如下。

1.定义一个接口

package com.yugioh.api.core.util.lock;

/**
 * 锁的接口
 *
 * @author lieber
 */
public interface ILock {

    /**
     * 默认加锁重试次数
     */
    int DEFAULT_LOCK_RETRY_TIMES = 3;

    /**
     * 默认解锁重试次数
     */
    int DEFAULT_UNLOCK_RETRY_TIMES = 3;

    /**
     * 默认加锁失败延时时间
     */
    long DEFAULT_LOCK_DELAYED_TIME = 1000;

    /**
     * 默认解锁失败延时时间
     */
    long DEFAULT_UNLOCK_DELAYED_TIME = 500;

    /**
     * 加锁
     *
     * @param lockId      锁唯一id
     * @param millisecond 释放锁的时间
     * @return 是否加锁成功
     */
    boolean lock(String lockId, long millisecond);

    /**
     * 加锁
     *
     * @param lockId      锁唯一id
     * @param millisecond 释放锁的时间
     * @param retry       加锁失败重试次数
     * @return 是否加锁成功
     */
    boolean lock(String lockId, long millisecond, int retry);

    /**
     * 加锁
     *
     * @param lockId      锁唯一id
     * @param millisecond 释放锁的时间
     * @param retry       加锁失败重试次数
     * @param delayed     每次重试间隔时间
     * @return 是否加锁成功
     */
    boolean lock(String lockId, long millisecond, int retry, long delayed);

    /**
     * 解锁
     *
     * @param lockId 锁唯一id
     * @return 是否解锁成功
     */
    boolean unlock(String lockId);

    /**
     * 解锁
     *
     * @param lockId 锁唯一id
     * @param retry  解锁失败重试次数
     * @return 是否解锁成功
     */
    boolean unlock(String lockId, int retry);

    /**
     * 解锁
     *
     * @param lockId  锁唯一id
     * @param retry   解锁失败重试次数
     * @param delayed 每次重试间隔时间
     * @return 是否解锁成功
     */
    boolean unlock(String lockId, int retry, long delayed);

    /**
     * 判断某个id是否已经锁住
     *
     * @param lockId 锁唯一id
     * @return true/false
     */
    boolean locked(String lockId);
}

2.定义加/解锁过程中的异常

package com.yugioh.api.core.util.lock;

/**
 * 锁异常
 *
 * @author lieber
 */
public class LockException extends RuntimeException {

    private static final long serialVersionUID = -4423361576822816712L;

    public LockException(String message) {
        super(message);
    }

    public LockException(String message, Throwable cause) {
        super(message, cause);
    }
}

3.实现Redis的加/解锁

package com.yugioh.api.core.util.lock.impl;

import com.yugioh.api.core.util.lock.ILock;
import com.yugioh.api.core.util.lock.LockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 基于redis的分布式锁实现
 *
 * @author lieber
 */
public class RedisDistributedLockImpl implements ILock {

    private final static Logger log = LoggerFactory.getLogger(RedisDistributedLockImpl.class);

    private final RedisTemplate<String, ?> redisTemplate;

    private RedisDistributedLockImpl() {
        throw new LockException("The Operation is not allowed, Please assign value to redisTemplate");
    }

    public RedisDistributedLockImpl(RedisTemplate<String, ?> redisTemplate) {
        if (redisTemplate == null) {
            throw new LockException("Can not assign null to redisTemplate");
        }
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean lock(String lockId, long millisecond) {
        return this.lock(lockId, millisecond, DEFAULT_LOCK_RETRY_TIMES, DEFAULT_LOCK_DELAYED_TIME);
    }

    @Override
    public boolean lock(String lockId, long millisecond, int retry) {
        return this.lock(lockId, millisecond, retry, DEFAULT_LOCK_DELAYED_TIME);
    }

    @Override
    public boolean lock(String lockId, long millisecond, int retry, long delayed) {
        Assert.isTrue(!StringUtils.isEmpty(lockId), "The lockId cannot be Null");
        Assert.isTrue(millisecond > 0, "The expiration  millisecond cannot less than 0");
        boolean success = false;
        int count = 0;
        while (count < retry && !success) {
            Boolean result = this.redisTemplate.opsForValue().setIfAbsent(lockId, null, millisecond, TimeUnit.MILLISECONDS);
            success = Objects.nonNull(result) && result;
            count++;
            // 延时
            try {
                Thread.sleep(delayed);
            } catch (InterruptedException e) {
                log.error(" lock lockId={}, millisecond={}, retry={}, delayed={} fail. cause exception: ", lockId, millisecond, retry, delayed, e);
            }
        }
        return success;
    }

    @Override
    public boolean unlock(String lockId) {
        return this.unlock(lockId, DEFAULT_UNLOCK_RETRY_TIMES, DEFAULT_UNLOCK_DELAYED_TIME);
    }

    @Override
    public boolean unlock(String lockId, int retry) {
        return this.unlock(lockId, retry, DEFAULT_UNLOCK_DELAYED_TIME);
    }

    @Override
    public boolean unlock(String lockId, int retry, long delayed) {
        Assert.isTrue(!StringUtils.isEmpty(lockId), "The lockId cannot be Null");
        boolean success = false;
        int count = 0;
        while (count < retry && !success) {
            Boolean result = redisTemplate.delete(lockId);
            success = Objects.nonNull(result) && result;
            count++;
            // 延时
            try {
                Thread.sleep(delayed);
            } catch (InterruptedException e) {
                log.error(" unlock lockId={}, retry={}, delayed={} fail. cause exception: ", lockId, retry, delayed, e);
            }
        }
        return success;
    }

    @Override
    public boolean locked(String lockId) {
        Boolean success = this.redisTemplate.hasKey(lockId);
        return Objects.nonNull(success) && success;
    }
}

至此实现了一个简单的基于Redis的分布式锁,还有许多值得优化的空间。

上一篇下一篇

猜你喜欢

热点阅读