cn.structure.starter.redis.lock.RedisDistributedLockImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of structure-redis-starter Show documentation
Show all versions of structure-redis-starter Show documentation
对spring-boot-starter-data-redis启动器进行封装正在意义上的零配置启动
The newest version!
package cn.structure.starter.redis.lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import java.util.ArrayList;
import java.util.List;
/**
*
* 分布式锁实现类
*
*
* @author chuck
*/
public class RedisDistributedLockImpl implements IDistributedLock {
private final Logger logger = LoggerFactory.getLogger(RedisDistributedLockImpl.class);
private final RedisTemplate redisTemplate;
private final ThreadLocal lockFlag = new ThreadLocal();
public RedisDistributedLockImpl(RedisTemplate redisTemplate) {
super();
this.redisTemplate = redisTemplate;
}
@Override
public boolean lock(String key, long expire, int retryTimes, long sleepMillis) {
boolean result = setRedis(key, expire);
// 如果获取锁失败,按照传入的重试次数进行重试
while ((!result) && retryTimes-- > 0) {
try {
logger.debug("lock failed, retrying...{}", retryTimes);
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
return false;
}
result = setRedis(key, expire);
}
return result;
}
private boolean setRedis(String key, long expire) {
try {
List keys = new ArrayList<>();
keys.add(key);
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy