詳見代碼:
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);
}
}