复制代码代码如下 :
package com.happyElements.odin.util;
static com.google.common.base.preconditions.checknotnull 가져 오기;
import org.jetbrains.annotations.notnull;
import com.happyElements.odin.jedis.jedisclient;
import com.happyElements.rdcenter.commons.util.datetimeutil;
/**
* 사용자 : Jude.wang
* 날짜 : 14-1-16
* 시간 : : 9:43
*/
공개 클래스 Concurrentutil {
공개 정적 최종 문자열 user_lock_key_format = "user_lock_%d_%s";
공개 정적 최종 문자열 custom_lock_format = "custom_lock_%s";
공개 정적 최종 Jedisclient redisclient = jedisclient.getInstance ();
공개 정적 최종 문자열 잠금 해제 = "0";
공개 정적 최종 문자열 잠금 = "1";
개인 정적 최종 최종 int max_repeat_times = 10;
@notnull
public static String buildUserLockey (long userId, @notnull 문자열 키) {
CheckNotNull (키);
return string.format (user_lock_key_format, userId, key);
}
@notnull
public static String buildCustOmlockey (@NotNull String Key) {
CheckNotNull (키);
return string.format (custom_lock_format, key);
}
/**
* 此方法可以因为拿不到锁而导致 작동 没有执行
*
* @param 키
* @see com.happyElements.odin.util.concurrentutil#buildCustomLockey (String)
* @see com.happyElements.odin.util.concurrentutil#buildUserLockey (long, string)
*
* @param 작동
* @throws com.happyElements.odin.util.concurrentutil.operationnotexecexception
* 작동 没有被执行
*/
public static void dojobwithlock (@notnull string key, @notnull ilockoperation 작동) throws OperationNoteXeCexception {
부울 잠긴 = 거짓;
노력하다 {
CheckNotNull (키);
CheckNotNull (작동);
잠금 = 잠금 (키);
} catch (Throwable t) {
새로운 OperationNoteXeCexception (키, t)을 던지십시오.
}
노력하다 {
if (잠금) {
// system.out.println (Thread.currentThread () + "/t" + "lock");
Operation.Dojob ();
} 또 다른 {
새로운 OperationNoteXeCexception (키)을 던지십시오.
}
} 마지막으로 {
if (잠금) {
잠금 해제 (키);
}
}
}
개인 정적 무효 잠금 해제 (문자열 키) {
노력하다 {
CheckNotNull (키);
String OldStatus = redisclient.getSet (키, 잠금 해제);
if (isunlocked (Oldstatus)) {
// lock-> dojob-> 过期-> 잠금 해제
// TODO 로그
}
} catch (Throwable t) {
// TODO 로그
}
// system.out.println (thread.currentThread () + "/t" + "Unlock");
}
개인 정적 부울 isunlocked (문자열 상태) {
반환 상태 == 널 || status.equals (잠금 해제);
}
개인 정적 부울 잠금 (문자열 키) {
부울 잠긴 = 거짓;
for (int i = 0; i <max_repeat_times; i ++) {
String OldStatus = redisclient.getSet (키, 잠금);
if (isunlocked (Oldstatus)) {
if (oldstatus == null) {
redisclient.expire (key, datetimeutil.minute_second * 5);
잠긴 = 참;
부서지다;
}
잠긴 = 참;
부서지다;
}
}
잠긴 반환;
}
공개 정적 인터페이스 ilockoperation {
void dojob ();
}
/**
* {@link com.happyElements.odin.util.concurrentutil.ilockoperation#dojob ()} 没有被执行 没有被执行
* 捕获到该异常可以 捕获到该异常可以 捕获到该异常可以, , ritry 本次操作 本次操作 {{@link com.happyElements.rdCenter.commons.throwable.heexception}}
*/
공개 정적 클래스 OperationNotexeCexception 확장 예외 {
public operationnotexecexception () {
}
공개 OperationNoteXeCexception (String S) {
슈퍼 (들);
}
공개 OperationNoteXeCexception (String S, Throwable Throwable) {
슈퍼 (s, 던질 가능);
}
공개 OperationNoteXeCexception (Throwable Throwable) {
슈퍼 (던질 가능);
}
}
}