import java.nio.charset.Charset;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;
@Component
public class RedisDistributedLockUtil {
private final Logger logger = LoggerFactory.getLogger(RedisDistributedLockUtil.class);
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final String UNLOCK_LUA;
//静态代码块lua脚本
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
sb.append("then ");
sb.append(" return redis.call(\"del\",KEYS[1]) ");
sb.append("else ");
sb.append(" return 0 ");
sb.append("end ");
UNLOCK_LUA = sb.toString();
}
public boolean setLock(String lockKey, long expire) {
try {
String uuid = UidUtils.randomUUID();
RedisCallback<Boolean> callback = (connection) -> {
return connection.set(lockKey.getBytes(Charset.forName("UTF-8")),
uuid.getBytes(Charset.forName(CharacterEncoding.UTF_8)), Expiration.seconds(expire),
RedisStringCommands.SetOption.SET_IF_ABSENT);
};
return (Boolean) redisTemplate.execute(callback);
} catch (Exception e) {
logger.error("set redis occured an exception:", e);
}
return false;
}
public boolean releaseLock(String lockKey, String requestId) {
RedisCallback<Boolean> callback = (connection) -> {
return connection.eval(UNLOCK_LUA.getBytes(), ReturnType.BOOLEAN, 1,
lockKey.getBytes(Charset.forName(CharacterEncoding.UTF_8)), requestId.getBytes(Charset.forName(CharacterEncoding.UTF_8)));
};
return (Boolean) redisTemplate.execute(callback);
}
public String get(String lockKey) {
try {
RedisCallback<String> callback = (connection) -> {
return new String(connection.get(lockKey.getBytes()), Charset.forName("UTF-8"));
};
return (String) redisTemplate.execute(callback);
} catch (Exception e) {
logger.error("get redis occurred an exception", e);
}
return null;
}
}