me.chanjar.weixin.common.util.locks.RedisTemplateSimpleDistributedLock Maven / Gradle / Ivy
The newest version!
package me.chanjar.weixin.common.util.locks;
import lombok.Getter;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* 实现简单的redis分布式锁, 支持重入, 不是红锁
*
* @see reids distlock
*/
public class RedisTemplateSimpleDistributedLock implements Lock {
@Getter
private final StringRedisTemplate redisTemplate;
@Getter
private final String key;
@Getter
private final int leaseMilliseconds;
private final ThreadLocal valueThreadLocal = new ThreadLocal<>();
public RedisTemplateSimpleDistributedLock( StringRedisTemplate redisTemplate, int leaseMilliseconds) {
this(redisTemplate, "lock:" + UUID.randomUUID().toString(), leaseMilliseconds);
}
public RedisTemplateSimpleDistributedLock( StringRedisTemplate redisTemplate, String key, int leaseMilliseconds) {
if (leaseMilliseconds <= 0) {
throw new IllegalArgumentException("Parameter 'leaseMilliseconds' must grate then 0: " + leaseMilliseconds);
}
this.redisTemplate = redisTemplate;
this.key = key;
this.leaseMilliseconds = leaseMilliseconds;
}
@Override
public void lock() {
while (!tryLock()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
while (!tryLock()) {
Thread.sleep(1000);
}
}
@Override
public boolean tryLock() {
String value = valueThreadLocal.get();
if (value == null || value.length() == 0) {
value = UUID.randomUUID().toString();
valueThreadLocal.set(value);
}
final byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
final byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy