在划水摸魚之際,突然聽到有的用戶反映增加了多條一樣的數據,這用戶立馬就不幹了,讓我們要馬上修復,不然就要投訴我們。
這下魚也摸不了了,只能去看看發生了什麼事情。據用戶反映,當時網絡有點卡,所以多點了幾次提交,最後發現出現了十幾條一樣的數據。
只能說現在的人都太心急了,連這幾秒的時間都等不了,慣的。心裏吐槽歸吐槽,這問題還是要解決的,不然老闆可不慣我。
其實想想就知道爲啥會這樣,在網絡延遲的時候,用戶多次點擊,最後這幾次請求都發送到了服務器訪問相關的接口,最後執行插入。
既然知道了原因,該如何解決。當時我的第一想法就是用註解 + AOP。通過在自定義註解裏定義一些相關的字段,比如過期時間即該時間內同一用戶不能重複提交請求。然後把註解按需加在接口上,最後在攔截器裏判斷接口上是否有該接口,如果存在則攔截。
解決了這個問題那還需要解決另一個問題,就是怎麼判斷當前用戶限定時間內訪問了當前接口。其實這個也簡單,可以使用Redis來做,用戶名 + 接口 + 參數啥的作爲唯一鍵,然後這個鍵的過期時間設置爲註解裏過期字段的值。設置一個過期時間可以讓鍵過期自動釋放,不然如果線程突然歇逼,該接口就一直不能訪問。
這樣還需要注意的一個問題是,如果你先去Redis獲取這個鍵,然後判斷這個鍵不存在則設置鍵;存在則說明還沒到訪問時間,返回提示。這個思路是沒錯的,但這樣如果獲取和設置分成兩個操作,就不滿足原子性了,那麼在多線程下是會出錯的。所以這樣需要把倆操作變成一個原子操作。
分析好了,就開幹。
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內同一用戶不允許重複訪問同一接口。使用的時候也可以傳入自定義的值。
我們只需要在對應的接口上添加該註解即可
@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) {
// 執行請求
result = pjp.proceed();
int status = responese.getStatus();
_log.debug("status = {}" + status);
// 釋放鎖,3s後讓鎖自動釋放,也可以手動釋放
// redisLock.releaseLock(key, key + sessionId);
return result;
} else {
// 失敗,認爲是重複提交的請求
return new UpmsResult(UpmsResultConstant.REPEAT_COMMIT, ValidationError.create(UpmsResultConstant.REPEAT_COMMIT.message));
}
}
}
攔截器定義的切點是NoRepeatCommit
註解,所以被NoRepeatCommit
註解標註的接口就會進入該攔截器。這裏我使用了account + "_" + sessionId + "_" + url + "_" + pg
作爲唯一鍵,表示某個用戶訪問某個接口。
這樣比較關鍵的一行是boolean isSuccess = redisLock.tryLock(key, key + sessionId, expire);
。可以看看RedisLock
這個類。
3、Redis工具類
上面討論過了,獲取鎖和設置鎖需要做成原子操作,不然併發環境下會出問題。這裏可以使用Redis的SETNX
命令。
/**
* redis分佈式鎖實現
* Lua表達式爲了保持數據的原子性
*/
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";
/**
* 加鎖
* 支持重複,線程安全
* 既然持有鎖的線程崩潰,也不會發生死鎖,因爲鎖到期會自動釋放
* @param lockKey 加鎖鍵
* @param userId 加鎖客戶端唯一標識(採用用戶id, 需要把用戶 id 轉換爲 String 類型)
* @param expireTime 鎖過期時間
* @return OK 如果key被設置了
*/
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 相對應,用作釋放鎖
* 解鎖必須與加鎖是同一人,其他人拿到鎖也不可以解鎖
*
* @param lockKey 加鎖鍵
* @param userId 解鎖客戶端唯一標識(採用用戶id, 需要把用戶 id 轉換爲 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不存在的情況下,纔會設置key,設置成功則返回OK。這樣就做到了查詢和設置原子性。
需要注意這裏在使用完jedis,需要進行close,不然耗盡連接數就完蛋了,我不會告訴你我把服務器搞掛了。
4、其他想說的
其實做完這三步差不多了,基本夠用。再考慮一些其他情況的話,比如在expire設置的時間內,我這個接口還沒執行完邏輯咋辦呢?
其實我們不用自己在這整破輪子,直接用健壯的輪子不好嗎?比如Redisson
,來實現分佈式鎖,那麼上面的問題就不用考慮了。有看門狗來幫你做,在鍵過期的時候,如果檢查到鍵還被線程持有,那麼就會重新設置鍵的過期時間。