作者:wingli
鏈接:https://juejin.cn/post/7182774381448282172
一、背景
1.為什么要做風控?
這不得拜產品大佬所賜
目前我們業務有使用到非常多的AI能力,如ocr識別、語音測評等,這些能力往往都比較費錢或者費資源,所以在產品層面也希望我們對用戶的能力使用次數做一定的限制,因此風控是必須的!
2.為什么要自己寫風控?
那么多開源的風控組件,為什么還要寫呢?是不是想重復發明輪子呀.
要想回答這個問題,需要先解釋下我們業務需要用到的風控(簡稱業務風控),與開源常見的風控(簡稱普通風控)有何區別:
| 風控型別 | 目的 | 物件 | 規則 |
|---|---|---|---|
| 業務風控 | 實作產品定義的一些限制,達到限制時,有具體的業務流程,如充值vip等 | 比較復雜多變的,例如針對用戶進行風控,也能針對用戶+年級進行風控 | 自然日、自然小時等 |
| 普通風控 | 保護服務或資料,攔截例外請求等 | 介面、部分可以加上簡單引數 | 一般用得更多的是滑動視窗 |
因此,直接使用開源的普通風控,一般情況下是無法滿足需求的
3.其它要求
支持實時調整限制:
很多限制值在首次設定的時候,基本上都是拍定的一個值,后續需要調整的可能性是比較大的,因此可調整并實時生效是必須的
二、思路
要實作一個簡單的業務風控組件,要做什么作業呢?
1.風控規則的實作
a.需要實作的規則:
- 自然日計數
- 自然小時計數
- 自然日+自然小時計數
自然日+自然小時計數 這里并不能單純地串聯兩個判斷,因為如果自然日的判定通過,而自然小時的判定不通過的時候,需要回退,自然日跟自然小時都不能計入本次呼叫!
b.計數方式的選擇:
目前能想到的會有:
- mysql+db事務
持久化、記錄可溯源、實作起來比較麻煩,稍微“重”了一點 - redis+lua
實作簡單,redis的可執行lua腳本的特性也能滿足對“事務”的要求 - mysql/redis+分布式事務
需要上鎖,實作復雜,能做到比較精確的計數,也就是真正等到代碼塊執行成功之后,再去操作計數
目前沒有很精確技術的要求,代價太大,也沒有持久化的需求,因此選用
redis+lua即可
2.呼叫方式的實作
a.常見的做法
先定義一個通用的入口
推薦一個開源免費的 Spring Boot 最全教程:
https://github.com/javastacks/spring-boot-best-practice
//簡化版代碼
@Component
class DetectManager {
fun matchExceptionally(eventId: String, content: String){
//呼叫規則匹配
val rt = ruleService.match(eventId,content)
if (!rt) {
throw BaseException(ErrorCode.OPERATION_TOO_FREQUENT)
}
}
}
在service中呼叫該方法
//簡化版代碼
@Service
class OcrServiceImpl : OcrService {
@Autowired
private lateinit var detectManager: DetectManager
/**
* 提交ocr任務
* 需要根據用戶id來做次數限制
*/
override fun submitOcrTask(userId: String, imageUrl: String): String {
detectManager.matchExceptionally("ocr", userId)
//do ocr
}
}
有沒有更優雅一點的方法呢? 用注解可能會更好一點(也比較有爭議其實,這邊先支持實作)
由于傳入的 content 是跟業務關聯的,所以需要通過Spel來將引數構成對應的content
三、具體實作
1.風控計數規則實作
a.自然日/自然小時
自然日/自然小時可以共用一套lua腳本,因為它們只有key不同,腳本如下:
//lua腳本
local currentValue = https://www.cnblogs.com/javastack/p/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] 是日/小時關聯的key,ARGV[1]是上限值,ARGV[2]是過期時間,回傳值則是當前計數值+1后的結果,(如果已經達到上限,則實際上不會計數)
b.自然日+自然小時
如前文提到的,兩個的結合實際上并不是單純的拼湊,需要處理回退邏輯
//lua腳本
local dayValue = 0;
local hourValue = 0;
local dayPass = true;
local hourPass = true;
local dayCurrentValue = https://www.cnblogs.com/javastack/p/redis.call('get', KEYS[1]);
if dayCurrentValue ~= false then
if tonumber(dayCurrentValue) < tonumber(ARGV[1]) then
dayValue = https://www.cnblogs.com/javastack/p/redis.call('INCR', KEYS[1]);
else
dayPass = false;
dayValue = https://www.cnblogs.com/javastack/p/tonumber(dayCurrentValue) + 1;
end;
else
redis.call('set', KEYS[1], 1, 'px', ARGV[3]);
dayValue = 1;
end;
local hourCurrentValue = https://www.cnblogs.com/javastack/p/redis.call('get', KEYS[2]);
if hourCurrentValue ~= false then
if tonumber(hourCurrentValue) < tonumber(ARGV[2]) then
hourValue = https://www.cnblogs.com/javastack/p/redis.call('INCR', KEYS[2]);
else
hourPass = false;
hourValue = https://www.cnblogs.com/javastack/p/tonumber(hourCurrentValue) + 1;
end;
else
redis.call('set', KEYS[2], 1, 'px', ARGV[4]);
hourValue = 1;
end;
if (not dayPass) and hourPass then
hourValue = https://www.cnblogs.com/javastack/p/redis.call('DECR', KEYS[2]);
end;
if dayPass and (not hourPass) then
dayValue = https://www.cnblogs.com/javastack/p/redis.call('DECR', KEYS[1]);
end;
local pair = {};
pair[1] = dayValue;
pair[2] = hourValue;
return pair;
其中 KEYS[1] 是天關聯生成的key, KEYS[2] 是小時關聯生成的key,ARGV[1]是天的上限值,ARGV[2]是小時的上限值,ARGV[3]是天的過期時間,ARGV[4]是小時的過期時間,回傳值同上
這里給的是比較粗糙的寫法,主要需要表達的就是,進行兩個條件判斷時,有其中一個不滿足,另一個都需要進行回退.
2.注解的實作
a.定義一個@Detect注解
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class Detect(
/**
* 事件id
*/
val eventId: String = "",
/**
* content的運算式
*/
val contentSpel: String = ""
)
其中content是需要經過運算式決議出來的,所以接受的是個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 = "https://www.cnblogs.com/javastack/p/@annotation(detect)")
fun operatorAnnotation(joinPoint: ProceedingJoinPoint, detect: Detect): Any? {
if (detect.eventId.isBlank() || detect.contentSpel.isBlank()){
throw illegalArgumentExp("@Detect config is not available!")
}
//轉換運算式
val expression = spelExpressionParser.parseExpression(detect.contentSpel)
val argMap = joinPoint.args.mapIndexed { index, any ->
"arg${index+1}" to any
}.toMap()
//構建背景關系
val context = StandardEvaluationContext().apply {
if (argMap.isNotEmpty()) this.setVariables(argMap)
}
//拿到結果
val content = expression.getValue(context)
detectManager.matchExceptionally(detect.eventId, content)
return joinPoint.proceed()
}
}
需要將引數放入到背景關系中,并起名為arg1、arg2....
四、測驗一下
1.寫法
使用注解之后的寫法:
//簡化版代碼
@Service
class OcrServiceImpl : OcrService {
@Autowired
private lateinit var detectManager: DetectManager
/**
* 提交ocr任務
* 需要根據用戶id來做次數限制
*/
@Detect(eventId = "ocr", contentSpel = "#arg1")
override fun submitOcrTask(userId: String, imageUrl: String): String {
//do ocr
}
}
2.Debug看看

- 注解值獲取成功
- 運算式決議成功
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2022最新版)
2.勁爆!Java 協程要來了,,,
3.Spring Boot 2.x 教程,太全了!
4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!
5.《Java開發手冊(嵩山版)》最新發布,速速下載!
覺得不錯,別忘了隨手點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/545526.html
標籤:Java
