利用Redis實現(xiàn)防止接口重復提交功能
前言
在劃水摸魚之際,突然聽到有的用戶反映增加了多條一樣的數(shù)據(jù),這用戶立馬就不干了,讓我們要馬上修復,不然就要投訴我們。
這下魚也摸不了了,只能去看看發(fā)生了什么事情。據(jù)用戶反映,當時網(wǎng)絡有點卡,所以多點了幾次提交,最后發(fā)現(xiàn)出現(xiàn)了十幾條一樣的數(shù)據(jù)。
只能說現(xiàn)在的人都太心急了,連這幾秒的時間都等不了,慣的。心里吐槽歸吐槽,這問題還是要解決的,不然老板可不慣我。
其實想想就知道為啥會這樣,在網(wǎng)絡延遲的時候,用戶多次點擊,最后這幾次請求都發(fā)送到了服務器訪問相關的接口,最后執(zhí)行插入。
既然知道了原因,該如何解決。當時我的第一想法就是用注解 + AOP。通過在自定義注解里定義一些相關的字段,比如過期時間即該時間內(nèi)同一用戶不能重復提交請求。然后把注解按需加在接口上,最后在攔截器里判斷接口上是否有該接口,如果存在則攔截。
解決了這個問題那還需要解決另一個問題,就是怎么判斷當前用戶限定時間內(nèi)訪問了當前接口。其實這個也簡單,可以使用Redis來做,用戶名 + 接口 + 參數(shù)啥的作為唯一鍵,然后這個鍵的過期時間設置為注解里過期字段的值。設置一個過期時間可以讓鍵過期自動釋放,不然如果線程突然歇逼,該接口就一直不能訪問。
這樣還需要注意的一個問題是,如果你先去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內(nèi)同一用戶不允許重復訪問同一接口。使用的時候也可以傳入自定義的值。
我們只需要在對應的接口上添加該注解即可
@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 { // 失敗,認為是重復提交的請求 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工具類
上面討論過了,獲取鎖和設置鎖需要做成原子操作,不然并發(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ā)生死鎖,因為鎖到期會自動釋放 * @param lockKey 加鎖鍵 * @param userId 加鎖客戶端唯一標識(采用用戶id, 需要把用戶 id 轉(zhuǎn)換為 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 轉(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不存在的情況下,才會設置key,設置成功則返回OK。這樣就做到了查詢和設置原子性。
需要注意這里在使用完jedis,需要進行close,不然耗盡連接數(shù)就完蛋了,我不會告訴你我把服務器搞掛了。
4、其他想說的
其實做完這三步差不多了,基本夠用。再考慮一些其他情況的話,比如在expire設置的時間內(nèi),我這個接口還沒執(zhí)行完邏輯咋辦呢?
其實我們不用自己在這整破輪子,直接用健壯的輪子不好嗎?比如Redisson
,來實現(xiàn)分布式鎖,那么上面的問題就不用考慮了。有看門狗來幫你做,在鍵過期的時候,如果檢查到鍵還被線程持有,那么就會重新設置鍵的過期時間。
到此這篇關于利用Redis實現(xiàn)防止接口重復提交功能的文章就介紹到這了,更多相關Redis防止接口重復提交內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
kubernetes環(huán)境部署單節(jié)點redis數(shù)據(jù)庫的方法
這篇文章主要介紹了kubernetes環(huán)境部署單節(jié)點redis數(shù)據(jù)庫的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01Redis序列化設置以及jetcache連接Redis序列化的設置過程
這篇文章主要介紹了Redis序列化設置以及jetcache連接Redis序列化的設置過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12Win10下 Redis啟動 錯誤1067導致進程意外終止的解決方法
這篇文章主要介紹了Win10下 Redis啟動 錯誤1067導致進程意外終止的完美解決方案,需要的朋友可以參考下2018-01-01Redis可視化工具Redis?Desktop?Manager的具體使用
本文主要介紹了Redis可視化工具Redis?Desktop?Manager的具體使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12