springboot+redis集群实现分布式锁

9 篇文章 1 订阅

springboot+redis集群实现分布式锁

前提

springboot+jedis访问redis集群,参考:
https://blog.csdn.net/sndayYU/article/details/119217214

代码

package org.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RedisLockService {

    @Autowired
    private RedisTemplate redisTemplate;

    private final static String UNLOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
            "return redis.call('del', KEYS[1]) " +
            "else return 0 end";

    public String tryLock(String key, int expireTime) {
        String uuid = UUID.randomUUID().toString();
        return tryLock(key, expireTime, uuid) ? uuid : null;
    }

    public String tryLock(String key, int expireTime, int retry, int interval) {
        String uuid = UUID.randomUUID().toString();
        try {
            int count = 1;
            while (count < retry) {
                if (tryLock(key, expireTime, uuid)) {
                    return uuid;
                }
                count++;
                TimeUnit.MILLISECONDS.sleep(interval);
            }
        } catch (InterruptedException e) {
            //
        }

        return tryLock(key, expireTime, uuid) ? uuid : null;
    }

    public boolean tryLock(String key, int expireTime, String uuid) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, uuid, expireTime, TimeUnit.SECONDS));
    }

    public boolean unlock(String key, String uuid) {
        // 集群下回报错
//        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(UNLOCK_SCRIPT, Long.class);
//        Long res = (Long)redisTemplate.execute(redisScript, Arrays.asList(key), uuid);
        Long res = (Long)redisTemplate.execute((RedisCallback) (connect) -> {
            Object nativeConnect = connect.getNativeConnection();
            if (nativeConnect instanceof JedisCluster) {
                 return ((JedisCluster) nativeConnect).eval(UNLOCK_SCRIPT, Arrays.asList(key), Arrays.asList(uuid));
            }
            return 0;
        });

        return 1 == res;
    }
}

测试

package org.example;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = MainApp.class)
@RunWith(SpringRunner.class)
public class RedisLockServiceTest {

    @Autowired
    private RedisLockService redisLockService;

    @Test
    public void testRedisLock() {
        String key = "key_test";
        String uuid = redisLockService.tryLock(key, 10);
        Assert.assertNotNull(uuid);
        Assert.assertTrue(redisLockService.unlock(key, uuid));
        Assert.assertFalse(redisLockService.unlock(key, uuid));
        Assert.assertFalse(redisLockService.unlock(key + "--test", uuid));


        key = "key_test2";
        uuid = redisLockService.tryLock(key, 10, 3, 1000);
        Assert.assertNotNull(uuid);
        Assert.assertTrue(redisLockService.unlock(key, uuid));
        Assert.assertFalse(redisLockService.unlock(key, uuid));
        Assert.assertFalse(redisLockService.unlock(key + "--test", uuid));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值