redis實現的分佈式鎖

詳見代碼:


package com.xhh.payment.lock;


import java.util.concurrent.TimeUnit;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;


/**    
 *     
 * 項目名稱:xhh-pay-service-http    
 * 類名稱:RedisLock    
 * 類描述:    
 * 創建人:zhuaijun    
 * 創建時間:2016年5月24日 下午12:54:57    
 * 修改人:zhuaijun    
 * 修改時間:2016年5月24日 下午12:54:57    
 * 修改備註:    
 * @version     
 *     
 */
public class RedisLock {
// beanFactory
private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/root-context-redis.xml");

// redis ops
private static RedisTemplate<String, String>  redisTemplate = (RedisTemplate<String, String>)applicationContext.getBean("redisTemplate");

// the name of lock
private static String LOCK_NAME = "LOCK_NAME";
/**    
  
* tryLock(這裏用一句話描述這個方法的作用) 

* @param timeout
* @return boolean   
  
* @throws    
  
* @since    
  
*/
public static boolean tryLock(long timeout) {
boolean isLock = redisTemplate.opsForValue().setIfAbsent(LOCK_NAME, LOCK_NAME);
long getTime = System.currentTimeMillis();

if (isLock) {
redisTemplate.expire(LOCK_NAME, 60, TimeUnit.SECONDS);
return true;
} else {
while (getTime + timeout > System.currentTimeMillis()) {
if (!redisTemplate.opsForValue().setIfAbsent(LOCK_NAME, LOCK_NAME)) {
try {
Thread.sleep(timeout/6);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}  else {
redisTemplate.expire(LOCK_NAME, 60, TimeUnit.SECONDS);
return true;
}
}

}

return false;
}

public static void releaseLock() {
redisTemplate.delete(LOCK_NAME);
}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章