import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import java.util.Collections;
/**
* @author hyx
*/
@Service
public class RedisLockService {
private static final Long SUCCESS = 1L;
@Autowired
private RedisTemplate redisTemplate;
/**
* 获取锁
*
* @param lockKey
* @param value
* @param expireTime 锁有效时间 单位-秒
* @return
*/
public boolean getLock(String lockKey, String value, int expireTime) {
boolean ret = false;
try {
//加锁命令,使用SETNX命令加锁,加锁成功返回1
String script = "if redis.call('setNx',KEYS[1],ARGV[1]) == 1 then if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Object result = redisTemplate.execute(redisScript, new StringRedisSerializer(),
new StringRedisSerializer(), Collections.singletonList(lockKey), value, String.valueOf(expireTime));
//判断加锁成功
if (SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* 释放锁
*
* @param lockKey
* @param value
* @return
*/
public boolean releaseLock(String lockKey, String value) {
//解锁命令,解锁成功返回1
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);
Object result = redisTemplate.execute(redisScript, new StringRedisSerializer(),
new StringRedisSerializer(), Collections.singletonList(lockKey), value);
//判断解锁成功
if (SUCCESS.equals(result)) {
return true;
}
return false;
}
}