Commit 72a2411d authored by zhiguo.liu's avatar zhiguo.liu

# 更改通过 Redis 上锁的方式,由 lua 脚本改成单条执行命令。

parent a5fd5e54
package cn.quantgroup.xyqb.Utils; package cn.quantgroup.xyqb.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript; import redis.clients.jedis.Jedis;
import org.springframework.data.redis.core.script.RedisScript;
import java.util.Arrays;
/** /**
* Created by zhiguo.liu on 2017/7/28. * Created by zhiguo.liu on 2017/7/28.
*/ */
public class RedisUtils { public class RedisUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class);
/** /**
* 通过 setnx + expire 命令,原子性给某个 key 上锁并设置过期时间 * 通过 setnx + expire 命令,原子性给某个 key 上锁并设置过期时间
* 上锁成功返回 true ,上锁失败返回 false. * 上锁成功返回 true ,上锁失败返回 false.
...@@ -21,12 +22,17 @@ public class RedisUtils { ...@@ -21,12 +22,17 @@ public class RedisUtils {
*/ */
public static boolean lock(RedisTemplate redisTemplate, String key, Integer expire) { public static boolean lock(RedisTemplate redisTemplate, String key, Integer expire) {
String lua = "local result = redis.call(\"setnx\",KEYS[1],\"1\")if result == 1 then redis.call(\"expire\",KEYS[1],ARGV[1]) end return result"; RedisConnection connection = null;
RedisScript<Long> script = new DefaultRedisScript<>(lua, Long.class); try {
connection = redisTemplate.getConnectionFactory().getConnection();
Object result = redisTemplate.execute(script, Arrays.asList(key), expire.toString()); Jedis jedis = (Jedis) connection.getNativeConnection();
if (result != null && result instanceof Long) { return jedis.set(key, "1", "nx", "ex", expire) != null;
return (Long) result == 1; } catch (Exception e) {
LOGGER.error("上锁出错:{}", e);
} finally {
if (connection != null) {
connection.close();
}
} }
return false; return false;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment