redis 分布式锁

慕课网上讲师廖师兄分享的

package bigdata.admin.redis;

import com.alibaba.nacos.client.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * redis分布式锁
 */
@Slf4j
@Component
public class RedisLock {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
    *@Description
    *@Date 14:10 2018/6/17
    *@Param value:当前时间+超时时间
    *@return
    **/
    public  boolean lock(String key,String value){
        if (redisTemplate.opsForValue().setIfAbsent(key,value)){
            return true;
        }
        //下面代码解决了 死锁问题 和 保证只有一个线程拿锁。
        /**1.死锁 。当相关代码之前上锁后,如果执行代码的过程中抛错了,
        那么就会出现没有解锁的问题,后续线程无法获得锁,也就出现了死锁的问题。
        而以下代码后有返回true的可能,也就解决了死锁问题。
        */
        /**2.保证只有一个线程拿锁。比如两个线程同时进入下面代码,并且其value都为B,currentValue = A。
        一条代码只可能一个线程执行。
        当第一个线程执行时,oldvalue = A,如果符合if条件成功拿锁。
        当第二个执行时oldValue就已经是B了,所以保证了只有一个线程拿锁。
        */
        String currentValue = redisTemplate.opsForValue().get(key);
        //如果锁过期
        if (!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()){
            //获取上一个锁的时间
            String oldValue = redisTemplate.opsForValue().getAndSet(key,value);
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)){
                return true;
            }
        }

        return false;
    }

    /**
    *@Description 解锁
    *@Date 14:25 2018/6/17
    *@Param
    *@return
    **/
    public void unlock(String key,String value){
        try{
            String currentValue = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)){
                redisTemplate.opsForValue().getOperations().delete(key);
            }
        }catch (Exception e){
            log.error("【redis分布式锁】解锁异常,{}",e);
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值