在劃水摸魚之際扩劝,突然聽到有的用戶反映增加了多條一樣的數(shù)據(jù)庸论,這用戶立馬就不干了,讓我們要馬上修復(fù)棒呛,不然就要投訴我們聂示。
這下魚也摸不了了,只能去看看發(fā)生了什么事情条霜。據(jù)用戶反映催什,當(dāng)時網(wǎng)絡(luò)有點卡涵亏,所以多點了幾次提交宰睡,最后發(fā)現(xiàn)出現(xiàn)了十幾條一樣的數(shù)據(jù)。
只能說現(xiàn)在的人都太心急了气筋,連這幾秒的時間都等不了拆内,慣的。心里吐槽歸吐槽宠默,這問題還是要解決的麸恍,不然老板可不慣我。
其實想想就知道為啥會這樣搀矫,在網(wǎng)絡(luò)延遲的時候抹沪,用戶多次點擊,最后這幾次請求都發(fā)送到了服務(wù)器訪問相關(guān)的接口瓤球,最后執(zhí)行插入融欧。
既然知道了原因,該如何解決卦羡。當(dāng)時我的第一想法就是用注解 + AOP噪馏。通過在自定義注解里定義一些相關(guān)的字段,比如過期時間即該時間內(nèi)同一用戶不能重復(fù)提交請求绿饵。然后把注解按需加在接口上欠肾,最后在攔截器里判斷接口上是否有該接口,如果存在則攔截拟赊。
解決了這個問題那還需要解決另一個問題刺桃,就是怎么判斷當(dāng)前用戶限定時間內(nèi)訪問了當(dāng)前接口。其實這個也簡單吸祟,可以使用Redis來做虏肾,用戶名 + 接口 + 參數(shù)啥的作為唯一鍵廓啊,然后這個鍵的過期時間設(shè)置為注解里過期字段的值。設(shè)置一個過期時間可以讓鍵過期自動釋放封豪,不然如果線程突然歇逼谴轮,該接口就一直不能訪問。
這樣還需要注意的一個問題是吹埠,如果你先去Redis獲取這個鍵第步,然后判斷這個鍵不存在則設(shè)置鍵;存在則說明還沒到訪問時間缘琅,返回提示粘都。這個思路是沒錯的,但這樣如果獲取和設(shè)置分成兩個操作刷袍,就不滿足原子性了翩隧,那么在多線程下是會出錯的。所以這樣需要把倆操作變成一個原子操作呻纹。
分析好了堆生,就開干。
1雷酪、自定義注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 防止同時提交注解
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatCommit {
// key的過期時間3s
int expire() default 3;
}
這里為了簡單一點淑仆,只定義了一個字段expire
,默認值為3哥力,即3s內(nèi)同一用戶不允許重復(fù)訪問同一接口蔗怠。使用的時候也可以傳入自定義的值。
我們只需要在對應(yīng)的接口上添加該注解即可
@NoRepeatCommit
或者
@NoRepeatCommit(expire = 10)
2吩跋、自定義攔截器
自定義好了注解寞射,那就該寫攔截器了。
@Aspect
public class NoRepeatSubmitAspect {
private static Logger _log = LoggerFactory.getLogger(NoRepeatSubmitAspect.class);
RedisLock redisLock = new RedisLock();
@Pointcut("@annotation(com.zheng.common.annotation.NoRepeatCommit)")
public void point() {}
@Around("point()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
// 獲取request
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = servletRequestAttributes.getRequest();
HttpServletResponse responese = servletRequestAttributes.getResponse();
Object result = null;
String account = (String) request.getSession().getAttribute(UpmsConstant.ACCOUNT);
User user = (User) request.getSession().getAttribute(UpmsConstant.USER);
if (StringUtils.isEmpty(account)) {
return pjp.proceed();
}
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
NoRepeatCommit form = method.getAnnotation(NoRepeatCommit.class);
String sessionId = request.getSession().getId() + "|" + user.getUsername();
String url = ObjectUtils.toString(request.getRequestURL());
String pg = request.getMethod();
String key = account + "_" + sessionId + "_" + url + "_" + pg;
int expire = form.expire();
if (expire < 0) {
expire = 3;
}
// 獲取鎖
boolean isSuccess = redisLock.tryLock(key, key + sessionId, expire);
// 獲取成功
if (isSuccess) {
// 執(zhí)行請求
result = pjp.proceed();
int status = responese.getStatus();
_log.debug("status = {}" + status);
// 釋放鎖锌钮,3s后讓鎖自動釋放桥温,也可以手動釋放
// redisLock.releaseLock(key, key + sessionId);
return result;
} else {
// 失敗,認為是重復(fù)提交的請求
return new UpmsResult(UpmsResultConstant.REPEAT_COMMIT, ValidationError.create(UpmsResultConstant.REPEAT_COMMIT.message));
}
}
}
攔截器定義的切點是NoRepeatCommit
注解轧粟,所以被NoRepeatCommit
注解標注的接口就會進入該攔截器策治。這里我使用了account + "_" + sessionId + "_" + url + "_" + pg
作為唯一鍵,表示某個用戶訪問某個接口兰吟。
這樣比較關(guān)鍵的一行是boolean isSuccess = redisLock.tryLock(key, key + sessionId, expire);
通惫。可以看看RedisLock
這個類混蔼。
3履腋、Redis工具類
上面討論過了,獲取鎖和設(shè)置鎖需要做成原子操作,不然并發(fā)環(huán)境下會出問題遵湖。這里可以使用Redis的SETNX
命令悔政。
/**
* redis分布式鎖實現(xiàn)
* Lua表達式為了保持數(shù)據(jù)的原子性
*/
public class RedisLock {
/**
* redis 鎖成功標識常量
*/
private static final Long RELEASE_SUCCESS = 1L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "EX";
private static final String LOCK_SUCCESS= "OK";
/**
* 加鎖 Lua 表達式。
*/
private static final String RELEASE_TRY_LOCK_LUA =
"if redis.call('setNx',KEYS[1],ARGV[1]) == 1 then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end";
/**
* 解鎖 Lua 表達式.
*/
private static final String RELEASE_RELEASE_LOCK_LUA =
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
/**
* 加鎖
* 支持重復(fù)延旧,線程安全
* 既然持有鎖的線程崩潰谋国,也不會發(fā)生死鎖,因為鎖到期會自動釋放
* @param lockKey 加鎖鍵
* @param userId 加鎖客戶端唯一標識(采用用戶id, 需要把用戶 id 轉(zhuǎn)換為 String 類型)
* @param expireTime 鎖過期時間
* @return OK 如果key被設(shè)置了
*/
public boolean tryLock(String lockKey, String userId, long expireTime) {
Jedis jedis = JedisUtils.getInstance().getJedis();
try {
jedis.select(JedisUtils.index);
String result = jedis.set(lockKey, userId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null)
jedis.close();
}
return false;
}
/**
* 解鎖
* 與 tryLock 相對應(yīng)迁沫,用作釋放鎖
* 解鎖必須與加鎖是同一人芦瘾,其他人拿到鎖也不可以解鎖
*
* @param lockKey 加鎖鍵
* @param userId 解鎖客戶端唯一標識(采用用戶id, 需要把用戶 id 轉(zhuǎn)換為 String 類型)
* @return
*/
public boolean releaseLock(String lockKey, String userId) {
Jedis jedis = JedisUtils.getInstance().getJedis();
try {
jedis.select(JedisUtils.index);
Object result = jedis.eval(RELEASE_RELEASE_LOCK_LUA, Collections.singletonList(lockKey), Collections.singletonList(userId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null)
jedis.close();
}
return false;
}
}
在加鎖的時候,我使用了String result = jedis.set(lockKey, userId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
集畅。set方法如下
/* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 GB).
Params:
key –
value –
nxxx – NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the key if it already exist.
expx – EX|PX, expire time units: EX = seconds; PX = milliseconds
time – expire time in the units of expx
Returns: Status code reply
*/
public String set(final String key, final String value, final String nxxx, final String expx,
final long time) {
checkIsInMultiOrPipeline();
client.set(key, value, nxxx, expx, time);
return client.getStatusCodeReply();
}
在key不存在的情況下近弟,才會設(shè)置key,設(shè)置成功則返回OK挺智。這樣就做到了查詢和設(shè)置原子性祷愉。
需要注意這里在使用完jedis,需要進行close赦颇,不然耗盡連接數(shù)就完蛋了二鳄,我不會告訴你我把服務(wù)器搞掛了。
4沐扳、其他想說的
其實做完這三步差不多了泥从,基本夠用句占。再考慮一些其他情況的話沪摄,比如在expire設(shè)置的時間內(nèi),我這個接口還沒執(zhí)行完邏輯咋辦呢纱烘?
其實我們不用自己在這整破輪子杨拐,直接用健壯的輪子不好嗎?比如Redisson
擂啥,來實現(xiàn)分布式鎖哄陶,那么上面的問題就不用考慮了。有看門狗來幫你做哺壶,在鍵過期的時候屋吨,如果檢查到鍵還被線程持有,那么就會重新設(shè)置鍵的過期時間山宾。