Skip to content

Instantly share code, notes, and snippets.

@asd1245dss
Created November 20, 2019 01:25
Show Gist options
  • Save asd1245dss/d4579e702669f1a4067004b56fb3b6d9 to your computer and use it in GitHub Desktop.
Save asd1245dss/d4579e702669f1a4067004b56fb3b6d9 to your computer and use it in GitHub Desktop.
Jedis jedis = new Jedis();
long result = jedis.setnx("namespace + orderId", "当前时间戳 + 过期时间");
// key不存在,获取锁成功
if (result == 1) {
System.out.println("key不存在,获取锁成功");
}
// key存在判断时间戳是否过期
if (result == 0) {
String expireDate = jedis.get("namespace + orderId");
int expireValue = expireDate.compareTo("当前时间戳 + 过期时间");
// 如果没有过期,获取锁失败
if (expireValue > 0) {
System.out.println("key存在,且没有过期,获取锁失败");
}
// 如果已经过期
if (expireValue <= 0) {
expireDate = jedis.getSet("namespace + orderId", "当前时间戳 + 过期时间");
expireValue = expireDate.compareTo("当前时间戳 + 过期时间");
// 如果没有过期,获取锁失败
if (expireValue > 0) {
System.out.println("key存在,且没有过期,获取锁失败");
} else {
System.out.println("key存在,且过期,获取锁成功");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment