springboot中实现Redis分布式锁

使用StringRedisTemplate来实现

1.添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.3.RELEASE</version>
        </dependency>

2.加锁/解锁

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author chengxn
 * @date 2020/7/14
 */
@Slf4j
@Component
public class RedisLock {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final Integer MINUTES = 3 * 60 * 1000;

    /**
     * 加锁
     *
     * @param key
     * @param timeStamp
     * @return
     */
    public boolean lock(String key, String timeStamp) {
        // 对应setnx命令
        if (stringRedisTemplate.opsForValue().setIfAbsent(key, timeStamp)) {
            return true;
        }
        // 判断锁超时 - 防止原来的操作异常,没有运行解锁操作  防止死锁
        String currentLock = stringRedisTemplate.opsForValue().get(key);
        // 如果锁过期 currentLock不为空且超过3分钟
        if (!Strings.isNullOrEmpty(currentLock) && System.currentTimeMillis() - Long.parseLong(currentLock) > MINUTES) {
            // 获取上一个锁的时间value 对应getset
            String preLock = stringRedisTemplate.opsForValue().getAndSet(key, timeStamp);

            // 假设两个线程同时进来这里,因为key被占用了,而且锁过期了。获取的值currentLock=A(get取的旧的值肯定是一样的),两个线程的timeStamp都是B,key都是K.锁时间已经过期了。
            // 而这里面的getAndSet一次只会一个执行,也就是一个执行之后,上一个的timeStamp已经变成了B。只有一个线程获取的上一个值会是A,另一个线程拿到的值是B。
            if (!Strings.isNullOrEmpty(preLock) && preLock.equals(currentLock)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 解锁
     *
     * @param key
     */
    public void unlock(String key) {
        try {
            String currentValue = stringRedisTemplate.opsForValue().get(key);
            if (!Strings.isNullOrEmpty(currentValue)) {
                // 删除锁状态
                stringRedisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            log.error("解锁异常{}", e);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值