Redis+aop實(shí)現(xiàn)接口防刷(冪等)的解決方案
冪等和接口防刷概念
這兩者其實(shí)是屬于不同的場景但是在一些情況下,實(shí)現(xiàn)方式上有異曲同工之妙。
防刷
顧名思義,想讓某個接口某個人在某段時間內(nèi)只能請求N次。一般是對一些不發(fā)人員用腳本對接口進(jìn)行大量請求,或者說利用腳本進(jìn)行秒殺。
冪等
冪等的數(shù)學(xué)概念
冪等是源于一種數(shù)學(xué)概念。其主要有兩個定義
如果在一元運(yùn)算中,x 為某集合中的任意數(shù),如果滿足 f(x) = f(f(x)) ,那么該 f 運(yùn)算具有冪等性,比如絕對值運(yùn)算 abs(a) = abs(abs(a)) 就是冪等性函數(shù)。
如果在二元運(yùn)算中,x 為某集合中的任意數(shù),如果滿足 f(x,x) = x,前提是 f 運(yùn)算的兩個參數(shù)均為 x,那么我們稱 f 運(yùn)算也有冪等性,比如求大值函數(shù) max(x,x) = x 就是冪等性函數(shù)。
冪等性在開發(fā)中的概念
在數(shù)學(xué)中冪等的概念或許比較抽象,但是在開發(fā)中冪等性是極為重要的。簡單來說,對于同一個系統(tǒng),在同樣條件下,一次請求和重復(fù)多次請求對資源的影響是一致的,就稱該操作為冪等的。比如說如果有一個接口是冪等的,當(dāng)傳入相同條件時,其效果必須是相同的。
特別是對于現(xiàn)在分布式系統(tǒng)下的 RPC 或者 Restful 接口互相調(diào)用的情況下,很容易出現(xiàn)由于網(wǎng)絡(luò)錯誤等等各種原因?qū)е抡{(diào)用的時候出現(xiàn)異常而需要重試,這時候就必須保證接口的冪等性,否則重試的結(jié)果將與第一次調(diào)用的結(jié)果不同,如果有個接口的調(diào)用鏈 A->B->C->D->E,在 D->E 這一步發(fā)生異常重試后返回了錯誤的結(jié)果,A,B,C也會受到影響,這將會是災(zāi)難性的。
為什么要進(jìn)行接口防刷(冪等)
在高并發(fā)場景下,可能會因?yàn)榫W(wǎng)絡(luò)或者服務(wù)器原因,造成延遲,具體來說就是,一個人點(diǎn)了一下,沒反應(yīng),又點(diǎn)了一下,但其實(shí)這兩次都發(fā)送請求成功了,這樣就可能造成數(shù)據(jù)不一致問題,同時還對資源進(jìn)行浪費(fèi)。同時就是有可能會有人用腳本大量訪問你的接口,造成資源崩潰。
解決方案
防刷
防刷的解決一般是不會用后端寫邏輯解決,一般可以在請求到nginx的時候就可以進(jìn)行判斷,然后加入黑名單,不需要請求到后端就能攔截,阿里的sentinel也可以解決這個問題
冪等
因?yàn)閮绲雀嗍窃诟卟l(fā)和分布式場景下,所以冪等更多是用redis做,畢竟redis一般就是用來解決分布式問題的
實(shí)戰(zhàn)
話不多說直接上代碼
首先架構(gòu)是用的xfg的ddd腳手架,架構(gòu)方面就不展開講了,我個人是寫在觸發(fā)器層的,因?yàn)檫壿嬓枰獙ontroller進(jìn)行操作,如果寫在別的層感覺很怪,如果寫在domain層應(yīng)該也是合理的,畢竟所有層都對domain有依賴,而且domain層本身是用來實(shí)現(xiàn)業(yè)務(wù)規(guī)則的。(這不是重點(diǎn),想聽ddd,我理解深一點(diǎn)以后單獨(dú)講)
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author: Larry * @Date: 2024 /03 /25 / 10:27 * @Description: */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RequestLimit { long time() default 10; int count() default 1; }
這個是對注解的定義,規(guī)定了時間范圍和次數(shù),默認(rèn)10秒內(nèi)只能進(jìn)行1次訪問
package cn.bugstack.aop; import cn.bugstack.config.RequestLimit; import cn.bugstack.infrastructure.util.RedisUtil; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.concurrent.TimeUnit; /** * @author: Larry * @Date: 2024 /03 /25 / 10:30 * @Description: */ @Aspect @Component @Slf4j public class LimitAOP { @Resource RedisUtil redisUtil; @Pointcut("execution(public * cn.bugstack.*..*.*(..))") public void LimitPointCut(){} //規(guī)定必須在上面路徑下同時方法上帶@requestLimit注解 @Around("LimitPointCut()&&@annotation(requestLimit)") public Object Before(ProceedingJoinPoint proceedingJoinPoint, RequestLimit requestLimit) throws Throwable { log.info("進(jìn)入aop中"); //根據(jù)注解獲取注解上的值 int limitCount = requestLimit.count(); System.out.println(limitCount+"limit"); long time = requestLimit.time(); //根據(jù)ServletRequestAttributes獲取當(dāng)前請求信息 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null) { HttpServletRequest request; request = requestAttributes.getRequest(); String ip = request.getRemoteAddr(); String url = request.getRequestURI(); //將ip和url拼接成唯一key String key = "request"+ip+url; log.info(key); if(redisUtil.get(key)!=null){ Integer count = (Integer) redisUtil.get(key); System.out.println(count+"==="+limitCount); if(count >= limitCount){ throw new LimitException("請不要頻繁操作"); } redisUtil.incr(key,1L); } else{ redisUtil.set(key,1,time); } } return proceedingJoinPoint.proceed(); } }
具體邏輯就是當(dāng)用戶發(fā)過來請求,(前提是controller上有對應(yīng)注解)進(jìn)入這個接口,然后根據(jù)ip和請求路徑作為key進(jìn)行判斷,如果此時redis有key,但是key的value不超過默認(rèn)次數(shù),就放行,如果沒有key,就根據(jù)其創(chuàng)建一個key設(shè)置過期時間為注解上的時間,然后放行,如果value過默認(rèn)次數(shù),就會被攔截,然后拋出一個自定義異常,可以在controller里捕獲并提示前端。為什么用ip+url,因?yàn)橛行┚W(wǎng)站是允許賬號多端同時使用的,這就會對一些用戶產(chǎn)生不友好的體驗(yàn),當(dāng)然一般情況下用userId也可以
package cn.bugstack.infrastructure.util; import org.springframework.data.redis.core.BoundListOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; @Component public class RedisUtil { private RedisTemplate<String, Object> redisTemplate; public RedisTemplate<String, Object> getRedisTemplate() { return redisTemplate; } @Resource public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } // public RedisUtil(RedisTemplate<String, Object> redisTemplate) { // this.redisTemplate = redisTemplate; // } /** * 向zset里存入數(shù)據(jù) * * @param key 鍵 * @param member 值 * @param score 分?jǐn)?shù) * @return */ public boolean addToZSet(String key, String member, double score) { return Boolean.TRUE.equals(redisTemplate.opsForZSet().add(key, member, score)); } /** * 指定緩存失效時間 * * @param key 鍵 * @param time 時間(秒) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根據(jù)key 獲取過期時間 * * @param key 鍵 不能為null * @return 時間(秒) 返回0代表為永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判斷key是否存在 * * @param key 鍵 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 刪除緩存 * * @param key 可以傳一個值 或多個 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key)); } } } //============================String============================= /** * 普通緩存獲取 * * @param key 鍵 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通緩存放入 * * @param key 鍵 * @param value 值 * @return true成功 false失敗 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通緩存放入并設(shè)置時間 * * @param key 鍵 * @param value 值 * @param time 時間(秒) time要大于0 如果time小于等于0 將設(shè)置無限期 * @return true成功 false 失敗 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 分布式鎖 * @param key 鎖住的key * @param lockExpireMils 鎖住的時長。如果超時未解鎖,視為加鎖線程死亡,其他線程可奪取鎖 * @return */ public boolean setNx(String key, Long lockExpireMils) { return (boolean) redisTemplate.execute((RedisCallback) connection -> { //獲取鎖 return connection.setNX(key.getBytes(), String.valueOf(System.currentTimeMillis() + lockExpireMils + 1).getBytes()); }); } /** * 遞增 * * @param key 鍵 * @param delta 要增加幾(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("遞增因子必須大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 遞減 * * @param key 鍵 * @param delta 要減少幾(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("遞減因子必須大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } //================================Map================================= /** * HashGet * * @param key 鍵 不能為null * @param item 項(xiàng) 不能為null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 獲取hashKey對應(yīng)的所有鍵值 * * @param key 鍵 * @return 對應(yīng)的多個鍵值 */ public Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 鍵 * @param map 對應(yīng)多個鍵值 * @return true 成功 false 失敗 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并設(shè)置時間 * * @param key 鍵 * @param map 對應(yīng)多個鍵值 * @param time 時間(秒) * @return true成功 false失敗 */ public boolean hmset(String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建 * * @param key 鍵 * @param item 項(xiàng) * @param value 值 * @return true 成功 false失敗 */ public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建 * * @param key 鍵 * @param item 項(xiàng) * @param value 值 * @param time 時間(秒) 注意:如果已存在的hash表有時間,這里將會替換原有的時間 * @return true 成功 false失敗 */ public boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 刪除hash表中的值 * * @param key 鍵 不能為null * @param item 項(xiàng) 可以使多個 不能為null */ public void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 判斷hash表中是否有該項(xiàng)的值 * * @param key 鍵 不能為null * @param item 項(xiàng) 不能為null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash遞增 如果不存在,就會創(chuàng)建一個 并把新增后的值返回 * * @param key 鍵 * @param item 項(xiàng) * @param by 要增加幾(大于0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash遞減 * * @param key 鍵 * @param item 項(xiàng) * @param by 要減少記(小于0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } //============================set============================= /** * 根據(jù)key獲取Set中的所有值 * * @param key 鍵 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根據(jù)value從一個set中查詢,是否存在 * * @param key 鍵 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將數(shù)據(jù)放入set緩存 * * @param key 鍵 * @param values 值 可以是多個 * @return 成功個數(shù) */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 將set數(shù)據(jù)放入緩存 * * @param key 鍵 * @param time 時間(秒) * @param values 值 可以是多個 * @return 成功個數(shù) */ public long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) { expire(key, time); } return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 獲取set緩存的長度 * * @param key 鍵 * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 移除值為value的 * * @param key 鍵 * @param values 值 可以是多個 * @return 移除的個數(shù) */ public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } //===============================list================================= /** * 獲取list緩存的內(nèi)容 * * @param key 鍵 * @param start 開始 * @param end 結(jié)束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 獲取list緩存的長度 * * @param key 鍵 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通過索引 獲取list中的值 * * @param key 鍵 * @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數(shù)第二個元素,依次類推 * @return */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 將list放入緩存 * * @param key 鍵 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將list放入緩存 * * @param key 鍵 * @param value 值 * @param time 時間(秒) * @return */ public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將list放入緩存 * * @param key 鍵 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將list放入緩存 * * @param key 鍵 * @param value 值 * @param time 時間(秒) * @return */ public boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根據(jù)索引修改list中的某條數(shù)據(jù) * * @param key 鍵 * @param index 索引 * @param value 值 * @return */ public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N個值為value * * @param key 鍵 * @param count 移除多少個 * @param value 值 * @return 移除的個數(shù) */ public long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 模糊查詢獲取key值 * * @param pattern * @return */ public Set keys(String pattern) { return redisTemplate.keys(pattern); } /** * 使用Redis的消息隊(duì)列 * * @param channel * @param message 消息內(nèi)容 */ public void convertAndSend(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } //=========BoundListOperations 用法 start============ /** * 將數(shù)據(jù)添加到Redis的list中(從右邊添加) * * @param listKey * @param timeout 有效時間 * @param unit 時間類型 * @param values 待添加的數(shù)據(jù) */ public void addToListRight(String listKey, long timeout, TimeUnit unit, Object... values) { //綁定操作 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey); //插入數(shù)據(jù) boundValueOperations.rightPushAll(values); //設(shè)置過期時間 boundValueOperations.expire(timeout, unit); } /** * 根據(jù)起始結(jié)束序號遍歷Redis中的list * * @param listKey * @param start 起始序號 * @param end 結(jié)束序號 * @return */ public List<Object> rangeList(String listKey, long start, long end) { //綁定操作 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey); //查詢數(shù)據(jù) return boundValueOperations.range(start, end); } /** * 彈出右邊的值 --- 并且移除這個值 * * @param listKey */ public Object rightPop(String listKey) { //綁定操作 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey); return boundValueOperations.rightPop(); } //=========BoundListOperations 用法 End============ }
然后這是對應(yīng)的redis工具類,記得自己配置序列化反序列化,或者直接用默認(rèn)的。
另一種思路
涉及數(shù),redis,統(tǒng)計(jì),大家能想到什么?沒錯--zset
可以采用一種滑動窗口的思想,(key同上文)每次請求往滑動窗口里存一條記錄,zset的score為這個接口請求時的時間戳,然后用當(dāng)前時間戳減去規(guī)定的限制時間的時間戳獲得一個窗口邊界,用zSetOperations.zCount(key, minScore, maxScore),請求在邊界窗口到現(xiàn)在的請求的數(shù)量,有多少條就是在限制的時間下發(fā)了多少次請求(比如過期時間是10分鐘,就是看過期時間到現(xiàn)在的請求的數(shù)量);這種方法個人感覺性能上不一定有提升,沒有進(jìn)行測試,不過這個方法對思維上的幫助和對rediszset用法的理解上都是挺有好處的,大家可以自己實(shí)踐一下。
結(jié)語
總之,冪等和接口防刷都是業(yè)務(wù)中常見的場景,redis,aop也是非常常用的技術(shù)棧,希望大家通過這個文章加深對業(yè)務(wù)、redis、springAOP的使用,后面考慮更ddd重構(gòu)老項(xiàng)目,mq等,不過時間不一定,敬請期待。
以上就是Redis+aop實(shí)現(xiàn)接口防刷(冪等)的解決方案的詳細(xì)內(nèi)容,更多關(guān)于Redis aop接口防刷的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Redis數(shù)據(jù)庫的應(yīng)用場景介紹
這篇文章主要介紹了Redis數(shù)據(jù)庫的應(yīng)用場景介紹,本文講解了MySql+Memcached架構(gòu)的問題、Redis常用數(shù)據(jù)類型、Redis數(shù)據(jù)類型應(yīng)用和實(shí)現(xiàn)方式、Redis實(shí)際應(yīng)用場景等內(nèi)容,需要的朋友可以參考下2015-06-06Redis教程(六):Sorted-Sets數(shù)據(jù)類型
這篇文章主要介紹了Redis教程(六):Sorted-Sets數(shù)據(jù)類型,本文講解了Sorted-Sets數(shù)據(jù)類型概述、相關(guān)命令列表、命令使用示例、應(yīng)用范圍等內(nèi)容,需要的朋友可以參考下2015-04-04異步redis隊(duì)列實(shí)現(xiàn) 數(shù)據(jù)入庫的方法
今天小編就為大家分享一篇異步redis隊(duì)列實(shí)現(xiàn) 數(shù)據(jù)入庫的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10Mac中Redis服務(wù)啟動時錯誤信息:NOAUTH Authentication required
這篇文章主要介紹了Mac中使用Redis服務(wù)啟動時錯誤信息:"NOAUTH Authentication required"問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08