風(fēng)控系統(tǒng)就該這么設(shè)計(jì)(萬能通用),穩(wěn)的一批!
點(diǎn)擊藍(lán)色“程序員黃小斜”關(guān)注我喲
加個“星標(biāo)”,每天和你一起多進(jìn)步一點(diǎn)點(diǎn)!

一、背景
1.為什么要做風(fēng)控?

這不得拜產(chǎn)品大佬所賜
目前我們業(yè)務(wù)有使用到非常多的AI能力,如ocr識別、語音測評等,這些能力往往都比較費(fèi)錢或者費(fèi)資源,所以在產(chǎn)品層面也希望我們對用戶的能力使用次數(shù)做一定的限制,因此風(fēng)控是必須的!
2.為什么要自己寫風(fēng)控?
那么多開源的風(fēng)控組件,為什么還要寫呢?是不是想重復(fù)發(fā)明輪子呀.
要想回答這個問題,需要先解釋下我們業(yè)務(wù)需要用到的風(fēng)控(簡稱業(yè)務(wù)風(fēng)控),與開源常見的風(fēng)控(簡稱普通風(fēng)控)有何區(qū)別:

因此,直接使用開源的普通風(fēng)控,一般情況下是無法滿足需求的
3.其它要求
支持實(shí)時調(diào)整限制
很多限制值在首次設(shè)置的時候,基本上都是拍定的一個值,后續(xù)需要調(diào)整的可能性是比較大的,因此可調(diào)整并實(shí)時生效是必須的
基于 Spring Boot + MyBatis Plus + Vue & Element 實(shí)現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能
項(xiàng)目地址:https://github.com/YunaiV/ruoyi-vue-pro 視頻教程:https://doc.iocoder.cn/video/
二、思路
要實(shí)現(xiàn)一個簡單的業(yè)務(wù)風(fēng)控組件,要做什么工作呢?
1.風(fēng)控規(guī)則的實(shí)現(xiàn)
a.需要實(shí)現(xiàn)的規(guī)則:
自然日計(jì)數(shù) 自然小時計(jì)數(shù) 自然日+自然小時計(jì)數(shù)
自然日+自然小時計(jì)數(shù) 這里并不能單純地串聯(lián)兩個判斷,因?yàn)槿绻匀蝗盏呐卸ㄍㄟ^,而自然小時的判定不通過的時候,需要回退,自然日跟自然小時都不能計(jì)入本次調(diào)用!
b.計(jì)數(shù)方式的選擇:
目前能想到的會有:
mysql+db事務(wù) 持久化、記錄可溯源、實(shí)現(xiàn)起來比較麻煩,稍微“重”了一點(diǎn) redis+lua 實(shí)現(xiàn)簡單,redis的可執(zhí)行l(wèi)ua腳本的特性也能滿足對“事務(wù)”的要求 mysql/redis+分布式事務(wù) 需要上鎖,實(shí)現(xiàn)復(fù)雜,能做到比較精確的計(jì)數(shù),也就是真正等到代碼塊執(zhí)行成功之后,再去操作計(jì)數(shù)
目前沒有很精確技術(shù)的要求,代價太大,也沒有持久化的需求,因此選用 redis+lua 即可
2.調(diào)用方式的實(shí)現(xiàn)
a.常見的做法 先定義一個通用的入口
//簡化版代碼
@Component
class DetectManager {
fun matchExceptionally(eventId: String, content: String){
//調(diào)用規(guī)則匹配
val rt = ruleService.match(eventId,content)
if (!rt) {
throw BaseException(ErrorCode.OPERATION_TOO_FREQUENT)
}
}
}
在service中調(diào)用該方法
//簡化版代碼
@Service
class OcrServiceImpl : OcrService {
@Autowired
private lateinit var detectManager: DetectManager
/**
* 提交ocr任務(wù)
* 需要根據(jù)用戶id來做次數(shù)限制
*/
override fun submitOcrTask(userId: String, imageUrl: String): String {
detectManager.matchExceptionally("ocr", userId)
//do ocr
}
}
有沒有更優(yōu)雅一點(diǎn)的方法呢? 用注解可能會更好一點(diǎn)(也比較有爭議其實(shí),這邊先支持實(shí)現(xiàn))
由于傳入的 content 是跟業(yè)務(wù)關(guān)聯(lián)的,所以需要通過Spel來將參數(shù)構(gòu)成對應(yīng)的content
基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 實(shí)現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能
項(xiàng)目地址:https://github.com/YunaiV/yudao-cloud 視頻教程:https://doc.iocoder.cn/video/
三、具體實(shí)現(xiàn)
1.風(fēng)控計(jì)數(shù)規(guī)則實(shí)現(xiàn)
a.自然日/自然小時
自然日/自然小時可以共用一套lua腳本,因?yàn)樗鼈冎挥?code style="font-size: 14px;padding: 2px 4px;border-radius: 4px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);background-color: rgba(27, 31, 35, 0.05);font-family: "Operator Mono", Consolas, Monaco, Menlo, monospace;word-break: break-all;">key不同,腳本如下:
//lua腳本
local currentValue = redis.call('get', KEYS[1]);
if currentValue ~= false then
if tonumber(currentValue) < tonumber(ARGV[1]) then
return redis.call('INCR', KEYS[1]);
else
return tonumber(currentValue) + 1;
end;
else
redis.call('set', KEYS[1], 1, 'px', ARGV[2]);
return 1;
end;
其中 KEYS[1] 是日/小時關(guān)聯(lián)的key,ARGV[1]是上限值,ARGV[2]是過期時間,返回值則是當(dāng)前計(jì)數(shù)值+1后的結(jié)果,(如果已經(jīng)達(dá)到上限,則實(shí)際上不會計(jì)數(shù))
b.自然日+自然小時 如前文提到的,兩個的結(jié)合實(shí)際上并不是單純的拼湊,需要處理回退邏輯
//lua腳本
local dayValue = 0;
local hourValue = 0;
local dayPass = true;
local hourPass = true;
local dayCurrentValue = redis.call('get', KEYS[1]);
if dayCurrentValue ~= false then
if tonumber(dayCurrentValue) < tonumber(ARGV[1]) then
dayValue = redis.call('INCR', KEYS[1]);
else
dayPass = false;
dayValue = tonumber(dayCurrentValue) + 1;
end;
else
redis.call('set', KEYS[1], 1, 'px', ARGV[3]);
dayValue = 1;
end;
local hourCurrentValue = redis.call('get', KEYS[2]);
if hourCurrentValue ~= false then
if tonumber(hourCurrentValue) < tonumber(ARGV[2]) then
hourValue = redis.call('INCR', KEYS[2]);
else
hourPass = false;
hourValue = tonumber(hourCurrentValue) + 1;
end;
else
redis.call('set', KEYS[2], 1, 'px', ARGV[4]);
hourValue = 1;
end;
if (not dayPass) and hourPass then
hourValue = redis.call('DECR', KEYS[2]);
end;
if dayPass and (not hourPass) then
dayValue = redis.call('DECR', KEYS[1]);
end;
local pair = {};
pair[1] = dayValue;
pair[2] = hourValue;
return pair;
其中 KEYS[1] 是天關(guān)聯(lián)生成的key, KEYS[2] 是小時關(guān)聯(lián)生成的key,ARGV[1]是天的上限值,ARGV[2]是小時的上限值,ARGV[3]是天的過期時間,ARGV[4]是小時的過期時間,返回值同上
這里給的是比較粗糙的寫法,主要需要表達(dá)的就是,進(jìn)行兩個條件判斷時,有其中一個不滿足,另一個都需要進(jìn)行回退.
2.注解的實(shí)現(xiàn)
a.定義一個@Detect注解
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class Detect(
/**
* 事件id
*/
val eventId: String = "",
/**
* content的表達(dá)式
*/
val contentSpel: String = ""
)
其中content是需要經(jīng)過表達(dá)式解析出來的,所以接受的是個String
b.定義@Detect注解的處理類
@Aspect
@Component
class DetectHandler {
private val logger = LoggerFactory.getLogger(javaClass)
@Autowired
private lateinit var detectManager: DetectManager
@Resource(name = "detectSpelExpressionParser")
private lateinit var spelExpressionParser: SpelExpressionParser
@Bean(name = ["detectSpelExpressionParser"])
fun detectSpelExpressionParser(): SpelExpressionParser {
return SpelExpressionParser()
}
@Around(value = "@annotation(detect)")
fun operatorAnnotation(joinPoint: ProceedingJoinPoint, detect: Detect): Any? {
if (detect.eventId.isBlank() || detect.contentSpel.isBlank()){
throw illegalArgumentExp("@Detect config is not available!")
}
//轉(zhuǎn)換表達(dá)式
val expression = spelExpressionParser.parseExpression(detect.contentSpel)
val argMap = joinPoint.args.mapIndexed { index, any ->
"arg${index+1}" to any
}.toMap()
//構(gòu)建上下文
val context = StandardEvaluationContext().apply {
if (argMap.isNotEmpty()) this.setVariables(argMap)
}
//拿到結(jié)果
val content = expression.getValue(context)
detectManager.matchExceptionally(detect.eventId, content)
return joinPoint.proceed()
}
}
需要將參數(shù)放入到上下文中,并起名為arg1、arg2....
四、測試一下
1.寫法
使用注解之后的寫法:
//簡化版代碼
@Service
class OcrServiceImpl : OcrService {
@Autowired
private lateinit var detectManager: DetectManager
/**
* 提交ocr任務(wù)
* 需要根據(jù)用戶id來做次數(shù)限制
*/
@Detect(eventId = "ocr", contentSpel = "#arg1")
override fun submitOcrTask(userId: String, imageUrl: String): String {
//do ocr
}
}
2.Debug看看

注解值獲取成功 表達(dá)式解析成功
— 【 THE END 】— 公眾號[程序員黃小斜]全部博文已整理成一個目錄,請?jiān)诠娞柪锘貜?fù)「m」獲取! 最近面試BAT,整理一份面試資料《Java面試BATJ通關(guān)手冊》,覆蓋了Java核心技術(shù)、JVM、Java并發(fā)、SSM、微服務(wù)、數(shù)據(jù)庫、數(shù)據(jù)結(jié)構(gòu)等等。
獲取方式:點(diǎn)“在看”,關(guān)注公眾號并回復(fù) PDF 領(lǐng)取,更多內(nèi)容陸續(xù)奉上。
文章有幫助的話,在看,轉(zhuǎn)發(fā)吧。
謝謝支持喲 (*^__^*)
