public class FenbushiSuo {
public static Jedis jedis = new Jedis(“localhost”, 6379);
public static boolean acquireLock(String lockname,String lock,Long acquireTime) {
acquireTime = System.currentTimeMillis() + acquireTime;
while (System.currentTimeMillis() < acquireTime) {
if (jedis.setnx(lockname, lock)==1) {
jedis.expire(lockname,20);
return true;
}else if(jedis.ttl(lockname)<0){
//没有设置过期时间
jedis.expire(lockname,20);
return true;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}
public static boolean releaseLock(String lockname,String lock){
Pipeline pipelined = jedis.pipelined();
while (true){
try {
pipelined.watch(lockname);
if(pipelined.get(lock).equals(lock)){
pipelined.multi();
pipelined.del(lockname);
List<Object> rs = pipelined.exec().get();
if(rs==null || rs.size()==0){
return false;
}
return true;
}
return true;
} catch (Exception e) {
continue;
}
}
}
public static void main(String[] args) {
String lock = UUID.randomUUID().toString();
boolean lockname = acquireLock("lockname", lock, 3000L);
System.out.println(lockname);
lockname = acquireLock("lockname", lock, 3000L);
System.out.println(lockname);
System.out.println(releaseLock("lockname", lock));
}
}