private StringRedisTemplate stringRedisTemplate;
public boolean waitLock(String key,String value,long waitTime){
long start = System.currentTimeMillis();
if(waitTime<=0){waitTime = timeout;}
SecureRandom random = new SecureRandom();
while (true){
if(System.currentTimeMillis()-start > waitTime){
return false;
}
Boolean absent = stringRedisTemplate.opsForValue().setIfAbsent(key, value, waitTime, TimeUnit.MILLISECONDS);
if(absent!=null && absent == true){
return true;
}
try{
Thread.sleep(random.nextInt(90)+10);
}catch (Exception e){e.printStackTrace();}
}
}
public boolean unlock(String key,String value){
try{
String script = "if redis.call('get', KEYS[1]) == KEYS[2] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
List<String> keys = Arrays.asList(key, value);
Object result = stringRedisTemplate.execute(redisScript, keys);
return RELEASE_SUCCESS.equals(result);
}catch (Exception e){
logger.error("redis 解锁错误:",e);
}
return false;
}
private RedisTemplate redisTemplate;
public boolean waitLock(String key,String value,long waitTime){
long start = System.currentTimeMillis();
if(waitTime<=0){waitTime = timeout;}
SecureRandom random = new SecureRandom();
while (true){
if(System.currentTimeMillis()-start > waitTime){
return false;
}
Boolean absent = redisTemplate.opsForValue().setIfAbsent(key, value, waitTime, TimeUnit.MILLISECONDS);
if(absent!=null && absent == true){
return true;
}
try{
Thread.sleep(random.nextInt(90)+10);
}catch (Exception e){e.printStackTrace();}
}
}
public boolean unlock(String key,String value){
try{
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Long status = (Long) this.redisTemplate.execute(redisScript,Collections.singletonList(key),value);
return RELEASE_SUCCESS.equals(status);
}catch (Exception e){
logger.error("redis 解锁错误:",e);
}
return false;
}