今天專案需要對介面進行限制訪問次數(某個時間段只允許訪問幾次) 專案經理說是做成乙個aop 小組件的形式,便於以後其他專案復用,這次我們是用redis+aop 實現的。
使用請求頭中的userid 來作為key 登陸次數作為value
請求時,判斷redis中是否有key ,if(沒有)
if(有) if(未超出)}
1.自定義註解類
/**
* @description: 介面限流自定義註解
* @author: xuxinku
* @date: 2020/4/6 14:18
* @modifieddate:
*/@documented
@target
(elementtype.method)
//代表方法級別
@inherited
//是指定某個自定義註解如果寫在了父類的宣告部分,那麼子類的宣告部分也能自動擁有該註解
@retention
(retentionpolicy.runtime)
public @inte***ce
accessrestriction
2.切面類實現
/**
* @description: 介面限流使用
* @author: xuxinku
* @date: 2020/4/6 14:18
* @modifieddate:
*/@aspect
@component
@slf4j
public
class
accessrestrictionaop
@before
("executeservice()&&@annotation(accessrestriction)"
)public
void
checkip
(joinpoint joinpoint, accessrestriction accessrestriction)
throws exception
//存在且大於規定次數
int frequency = integer.
valueof
(redistemplate.
opsforvalue()
.get
(key)).
intvalue()
;if(!stringutils.
isempty
(oldkay)
&& frequency > accessrestriction.
count()
)//次數+1
int i = frequency +1;
//更新記錄次數
redistemplate.
opsforvalue()
.set
(key, i+"",
0); log.
info
("開始記錄操作資訊 ");
system.out.
println
("請求次數*****》"
+oldkay)
; system.out.
println
("key*****》"
+key)
; log.
info
("記錄操作資訊成功");
}
3.loginaop工具
/**
* 必須新增這兩個註解:component: 泛指元件,講該類納入bean中;
* aspect: 通過該註解及表示式就可以輕鬆的使用pojo來定義切面
* * @author tdh
*/@aspect
@slf4j
@component
public
class
loginaop
if(stringutils.
isblank
(usercode)
)else
}/**
* 獲取分支機構編碼
** @return
*/public
static string getbranchcode()
else
}/**
* 獲取總公司機構編碼
** @return
*/public
static string getparentcode()
else
}/**
* 獲取使用者名稱
** @return
*/public
static string getusername()
else
}/**
* 定義攔截規則:攔截標有com.sheetchrist.annotation.login類中註解的所有方法com.flow.controller.flowcontroller
*/@pointcut
("execution(public * com.*.controller.*.*(..))"
)public
void
loginmethodpointcut()
@around
("loginmethodpointcut()"
)public object interceptor
(proceedingjoinpoint point)
throws throwable
public
static string getipaddr()
if(ip == null || ip.
length()
==0||"unknown"
.equalsignorecase
(ip))if
(ip == null || ip.
length()
==0||"unknown"
.equalsignorecase
(ip))if
("0:0:0:0:0:0:0:1"
.equals
(ip))if
(ip.
split
(","
).length >1)
return ip;
}}
4.註解的使用60秒 5次
@accessrestriction
(t =
60, count =5)
(value =
"/testaop2"
)public
void
testaop2()
測試:
每天記錄發現的問題,不進步就是在退步
介面限流演算法
在開發高併發系統時,有三把利器來保護系統 快取 降級和限流。下面來看看限流量的一些演算法 1.計數器法 它是限流演算法中最簡單最容易的一種演算法,比如我們要求某乙個介面,1分鐘內的請求不能超過10次,我們可以在開始時設定乙個計數器,每次請求,該計數器 1 如果該計數器的值大於10並且與第一次請求的時...
介面限流演算法小記
高併發系統中保護系統的三把利器 快取 降級 限流 快取 快取的目的是提公升系統訪問速度和增大系統處理容量 降級 降級是當伺服器壓力劇增的情況下,根據當前業務情況及流量對一些服務和頁面有策略的降級,以此釋放伺服器資源以保證核心任務的正常執行 限流 限流的目的是通過對併發訪問 請求進行限速,或者對乙個時...
介面限流 限制介面的訪問頻率
限流,顧名思義,就是限制對 api 的呼叫頻率。每一次 api 呼叫,都要花費伺服器的資源,因此很多 api 不會對使用者無限次地開放,請求達到某個次數後就不再允許訪問了,或者一段時間內,最多隻允許訪問 api 指定次數。目前,我們的介面是沒有任何限流措施的,只要使用者呼叫介面,伺服器就會處理並返回...