import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public
class
RedisLock {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private
StringRedisTemplate redisTemplate;
public
boolean lock(String key, String value) {
if
(redisTemplate.opsForValue().setIfAbsent(key, value)) {
redisTemplate.expire(key, lockTime, TimeUnit.SECONDS);
return
true;
}
String currentValue = redisTemplate.opsForValue().get(key);
if
(!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()) {
String oldValues = redisTemplate.opsForValue().getAndSet(key, value);
if
(!StringUtils.isEmpty(oldValues) && oldValues.equals(currentValue)) {
return
true;
}
}
return
false;
}
public
void unlock(String key, String value) {
try
{
String currentValue = redisTemplate.opsForValue().get(key);
if
(!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
redisTemplate.opsForValue().getOperations().
delete
(key);
}
}
catch
(Exception e) {
logger.error(
"redis分布式锁解锁异常,{}"
, e);
}
}
}