Commit 1d5e974f authored by zhiguo.liu's avatar zhiguo.liu

# 添加 RedisUtils 类。

parent 4b2bffa3
package cn.quantgroup.xyqb.Utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import java.util.Arrays;
/**
* Created by zhiguo.liu on 2017/7/28.
*/
public class RedisUtils {
/**
* 通过 setnx + expire 命令,原子性给某个 key 上锁并设置过期时间
* 上锁成功返回 true ,上锁失败返回 false.
*
* @param redisTemplate
* @param key
* @param expire
* @return
*/
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";
RedisScript<Long> script = new DefaultRedisScript<>(lua, Long.class);
Object result = redisTemplate.execute(script, Arrays.asList(key), expire.toString());
if (result != null && result instanceof Long) {
return (Long) result == 1;
}
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