说一说工作中用到的简单的redis分布式锁

redis分布式锁

    package com.nio.otd.lop.inventory.util;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.core.StringRedisTemplate;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * @Auther: turbo.cai
     * @Date: 2019/7/25 14:42
     * @Description:
     */
    @Slf4j
    public class MyRedisUtils {
        @Autowired
        StringRedisTemplate stringRedisTemplate;
    
        /**
         *
         * @param lockKey
         * @param lockTime 过期时间
         * @return
         */
        public long lock(String lockKey, Long lockTime) {
            Long lockValue = System.currentTimeMillis() + lockTime;
            //定义一个时间,在指定时间内可重试获取锁
            Long waitTime = System.currentTimeMillis() + 1000L;
            Boolean flag = stringRedisTemplate.execute((RedisCallback<Boolean>) e -> {
                Boolean success = false;
                try {
                    do {
                        success = e.setNX(lockKey.getBytes(), lockValue.toString().getBytes());
                        if (success) {
                            return success;
                        }
                        Thread.sleep(200);//第一次获取失败,隔200毫秒重试
                    } while (System.currentTimeMillis() < waitTime);//即在1000毫秒内获取锁失败还可以不断重试获取锁
                } catch (Throwable ex) {
                    ex.printStackTrace();
                }
                return success;
            });
            if (flag) {
                //加锁成功,设置过期时间
                stringRedisTemplate.expire(lockKey, lockTime, TimeUnit.MILLISECONDS);
                return lockValue;
            }
            return -1;
        }
    
        public void unlock(String lockKey,long lockValue){
            //根据key获取redis存入的value
            String result = stringRedisTemplate.opsForValue().get(lockKey);
            Long oldValue = result == null?null:Long.valueOf(result);
            if (oldValue != null && oldValue == lockValue){
                stringRedisTemplate.delete(lockKey);
            }else {
                log.info("非加锁者,等待过期时间结束后释放锁");
            }
        }
    }
    


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值