前提
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));
}
}