Redis分布式锁Java代码实现

#Redis分布式锁Java代码实现

/**
 * redis分布式锁 可重入
 * */
public class RedisDistributedLock implements Lock {

    private StringRedisTemplate stringRedisTemplate;

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

    public RedisDistributedLock(StringRedisTemplate stringRedisTemplate, String lockName) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.lockName = lockName;
        this.uuidValue = IdUtil.simpleUUID() + ":" + Thread.currentThread().getId();
        this.expireTime = 50L;
    }

    @Override
    public void lock() {
        tryLock();
    }


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

    @Override
    public boolean tryLock(long time, @NotNull TimeUnit unit) throws InterruptedException {
        if (time == -1L){
            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])   " +
                            "else   " +
                                    " return 0  " +
                            "end";
            while(!stringRedisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList(lockName), uuidValue, expireTime)) {
                // 暂停60毫秒
                try { TimeUnit.MILLISECONDS.sleep(60);} catch (InterruptedException e) { e.printStackTrace();};
            }
            renewExpire();
            return true;
        }
        return false;
    }

    // 自动续期  watch dog的思想
    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() {
                if (stringRedisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList(lockName), uuidValue, expireTime)){
                    renewExpire();
                }
            }
        }, (this.expireTime * 1000) / 3);
    }

    @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";
        Long flag = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(lockName), uuidValue, expireTime);
        if (flag == null){
            throw new RuntimeException("this lock doesn't not exists!!!!!");
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

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

### Java 实现 Redis 分布式锁 #### 使用 Jedis 客户端实现分布式锁 下面展示了一个利用 `Jedis` 库操作 Redis 来创建分布式锁的方法: ```java import redis.clients.jedis.Jedis; public class DistributedLock { /** * 尝试获取分布式锁. * * @param jedis 连接实例 * @param lockKey 锁名称对应的key * @param requestId 请求唯一标识符 * @param expireTime 锁的有效期(毫秒) * @return 是否成功获得锁 */ public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, "NX", "PX", expireTime); return "OK".equals(result); // 如果返回值为 OK 表明加锁成功[^3] } /** * 释放分布式锁. * * @param jedis 连接实例 * @param lockKey 锁名称对应的key * @param requestId 请求唯一标识符 */ public static void releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then " + "return redis.call('del', KEYS[1]) " + "else " + "return 0 end"; jedis.eval(luaScript, java.util.Collections.singletonList(lockKey), java.util.Collections.singletonList(requestId)); } } ``` 这段代码定义了两个主要函数:一个是用来尝试获取锁的 `tryGetDistributedLock()` 函数,另一个是用来安全地释放锁的 `releaseDistributedLock()` 函数。为了确保只有一个客户端能够删除自己拥有的锁而不会影响到其他的锁,在解锁的时候采用了 Lua 脚本来原子化地完成这个过程。 当调用者想要获取某个资源上的独占访问权时,应该先调用 `tryGetDistributedLock()` 方法去请求锁;一旦获得了锁就可以放心大胆地对该共享资源进行读取或修改操作;处理完毕之后记得要尽快调用 `releaseDistributedLock()` 去主动释放掉所持之锁以便让其他等待中的进程有机会继续运行下去[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值