Redis实现分布式锁

package com.example.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;


public class RedisDistributedLock implements Lock {


    @Autowired
    private RedisTemplate redisTemplate;

    private String lockName;  //KEYS[1]
    private String uuidValue; //ARGV[1]
    private Long expireTime;   //ARGV[2]

    public RedisDistributedLock(RedisTemplate redisTemplate, String lockName) {
        this.redisTemplate= redisTemplate;
        this.lockName = lockName;
        this.uuidValue=java.util.UUID.randomUUID().toString().replaceAll("-","")+":"+Thread.currentThread().getId();
        this.expireTime=50L;
    }

    @Override
    public void lock() {
        //对外暴露的是lock与unlock,但实际调用得是tryLock,然后在调用tryLock(-1L,TimeUnit.SECONDS)
        tryLock();

    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        try { tryLock(-1L,TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    //实际干活得方法
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        if(time==-1){

            String script=
                    "if redis.call('exists',KEYS[1]) == 0 " +
                        "or redis.call('hexists',KEYS[1],ARGV[1]) == 1 then" +
                        "redis.call('hincrby',KEYS[1],ARGV[1],1)" +
                        "redis.call('expire',KEYS[1],ARGV[2])" +
                        "return 1 " +
                    "else " +
                        "return 0 " +
                    "end";
            Object execute = redisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList(lockName), uuidValue, String.valueOf(expireTime));
            Boolean flag=(Boolean) execute;
            while(!flag){

            }
        }
        return false;
    }

    //下面这两个方法用不到
    @Override
    public void unlock() {
        String script=
                "if " +
                        "redis.call('hexists',KEYS[1],ARGV[1]) == 0 then " +
                        "return nil" +
                "elseif redis.call('hincrby',KEYS[1],ARGV[1],-1) == 0 then" +
                        "return redis.call('del',KEYS[1])" +
                "else return 0" +
                "end";
        Object execute = redisTemplate.execute(new DefaultRedisScript(script, Long.class), Arrays.asList(lockName), uuidValue);
        Long flag=(Long) execute;
        if(flag==null){
            throw  new RuntimeException("锁不存在");
        }

    }

    //自动续期
    private void renewExpire(){
        String script="" +
                "if redis.call('hexists',KEYS[1],ARGV[1]) ==1 then" +
                    "return redis.call('expire',KEYS[1],ARGV[2])" +
                "else return 0 " +
                "end";

        //每隔一定时间就去执行一次
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
               Boolean execute =(Boolean) redisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList(lockName), uuidValue, String.valueOf(expireTime));
                if(execute){
                    renewExpire();
                }
            }
        },(this.expireTime*1000)/2);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值