redis做分布式锁 java demo

package lockUtil;


import java.util.concurrent.TimeUnit;


public class RedisLock {
private static final String LOCK_KEY = "lock_key";
private static final long EXPIRE_TIME = 1000;


public boolean tryLock(String subkey,long timeout,TimeUnit unit){
//  
// String key=LOCK_KEY+subkey;
// try{
// Jedis jedis=null;
// try{
// jedis=getConnection();
// if(jedis==null){
// return Boolean.FALSE;
// }
// }
//
// long nano=System.nanoTime();
//
// do{
//   long i=jedis.setNX(key,key);
//
//   if(i==1){
//   jedis.expire(key,EXPIRE_TIME);
//   return Boolean.TRUE;
//   }else{
//   //锁已经被占了
//   String desc=jedis.get(key);
//   logger.debug("key:"+key+"locked by another bussiness:"+desc);
//   }
//   
//   if(timeout==0){//取不到锁时,不等待直接返回
//  break; 
//   }
// Thread.sleep(200);
//
// }while((System.nanoTime()-nano)<unit.toNanos(timeout));
// return Boolean.FALSE;
// }catch(Exception e){
// e.printStackTrace();
// }
return Boolean.FALSE;
}
/**

* @Method: lock  
* @Description: 如果锁空闲立即返回,获取失败,一直等待
* @param subKey
* @return boolean (返回类型描述) 
* @throws  
* @author : wangshuai 
* @CreateDate : 2017年6月19日 下午4:48:09
*/
public boolean lock(String subKey){
String key=LOCK_KEY+subKey;
Jedis jedis=null;
boolean isLock=false;
try{
jedis=getConnection();
if(jedis==null){
return isLock;
}
while(true){
long i=jedis.setNX(key,key);
if(i==1){
jedis.expire(key,EXPIRE_TIME);
isLock=true;
}else{//存在锁
String desc=jedis.get(key);
logger.debug("key:"+key+"locked bu another business"+desc);
isLock=false;
}
Thread.sleep(500);
}
}catch(Exception e){
e.printStackTrace();
return isLock;
}

return isLock;
}
/*释放锁*/
public void unlock(Sting subKey){
String key = LOCK_KEY + subKey;  
 Jedis jedis = null;  
 try {  
  jedis = getConnection();  
  if (jedis == null) {  
   return;  
  }  
  jedis.del(key);  
  logger.debug("release lock, keys :" + key);  
 } catch (JedisConnectionException je) {  
  logger.error(je.getMessage(), je);  
 } catch (Exception e) { 
 e.printStackTrace();
 }  
}



}

猜你喜欢

转载自blog.csdn.net/jack_shuai/article/details/73469429
今日推荐