posted on 2014-01-15 19:00
云云 阅读(13285)
评论(1) 编辑 收藏
public static boolean acquirelock(string lock) {
// 1. 通过setnx试图获取一个lock
boolean success = false;
jedis jedis = pool.getresource();
long value = system.currenttimemillis() expired 1;
system.out.println(value);
long acquired = jedis.setnx(lock, string.valueof(value));
//setnx成功,则成功获取一个锁
if (acquired == 1)
success = true;
//setnx失败,说明锁仍然被其他对象保持,检查其是否已经超时
else {
long oldvalue = long.valueof(jedis.get(lock));
//超时
if (oldvalue < system.currenttimemillis()) {
string getvalue = jedis.getset(lock, string.valueof(value));
// 获取锁成功
if (long.valueof(getvalue) == oldvalue)
success = true;
// 已被其他进程捷足先登了
else
success = false;
}
//未超时,则直接返回失败
else
success = false;
}
pool.returnresource(jedis);
return success;
}
//释放锁
public static void releaselock(string lock) {
jedis jedis = pool.getresource();
long current = system.currenttimemillis();
// 避免删除非自己获取得到的锁
if (current < long.valueof(jedis.get(lock)))
jedis.del(lock);
pool.returnresource(jedis);
}
//--------------------------
public long acquirelock(final string lockname,final long expire){
return redistemplate.execute(new rediscallback() {
public long doinredis(redisconnection connection) {
byte[] lockbytes = redistemplate.getstringserializer().serialize(lockname);
boolean locked = connection.setnx(lockbytes, lockbytes);
connection.expire(lockbytes, expire);
if(locked){
return 1l;
}
return 0l;
}
});
}
//原子操作 -----------------------
public string getandset(final string key,final string value){
return redistemplate.execute(new rediscallback() {
@override
public string doinredis(redisconnection connection)
throws dataaccessexception {
byte[] result = connection.getset(redistemplate.getstringserializer().serialize(key),
redistemplate.getstringserializer().serialize(value));
if(result!=null){
return new string(result);
}
return null;
}
});
}