這篇文章主要講解了“怎么使用Java編寫一個簡單的風控組件”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么使用Java編寫一個簡單的風控組件”吧!
這不得拜產品大佬所賜
目前我們業務有使用到非常多的AI能力,如ocr識別、語音測評等,這些能力往往都比較費錢或者費資源,所以在產品層面也希望我們對用戶的能力使用次數做一定的限制,因此風控是必須的!
那么多開源的風控組件,為什么還要寫呢?是不是想重復發明輪子呀.

要想回答這個問題,需要先解釋下我們業務需要用到的風控(簡稱業務風控),與開源常見的風控(簡稱普通風控)有何區別:
| 風控類型 | 目的 | 對象 | 規則 |
|---|---|---|---|
| 業務風控 | 實現產品定義的一些限制,達到限制時,有具體的業務流程,如充值vip等 | 比較復雜多變的,例如針對用戶進行風控,也能針對用戶+年級進行風控 | 自然日、自然小時等 |
| 普通風控 | 保護服務或數據,攔截異常請求等 | 接口、部分可以加上簡單參數 | 一般用得更多的是滑動窗口 |
因此,直接使用開源的普通風控,一般情況下是無法滿足需求的
支持實時調整限制
很多限制值在首次設置的時候,基本上都是拍定的一個值,后續需要調整的可能性是比較大的,因此可調整并實時生效是必須的
要實現一個簡單的業務風控組件,要做什么工作呢?
a.需要實現的規則
自然日計數
自然小時計數
自然日+自然小時計數
自然日+自然小時計數 這里并不能單純地串聯兩個判斷,因為如果自然日的判定通過,而自然小時的判定不通過的時候,需要回退,自然日跟自然小時都不能計入本次調用!
b.計數方式的選擇
目前能想到的會有:
mysql+db事務
持久化、記錄可溯源、實現起來比較麻煩,稍微“重”了一點
redis+lua
實現簡單,redis的可執行lua腳本的特性也能滿足對“事務”的要求
mysql/redis+分布式事務
需要上鎖,實現復雜,能做到比較精確的計數,也就是真正等到代碼塊執行成功之后,再去操作計數
目前沒有很精確技術的要求,代價太大,也沒有持久化的需求,因此選用 redis+lua 即可
a.常見的做法
先定義一個通用的入口
//簡化版代碼
@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
a.自然日/自然小時
自然日/自然小時可以共用一套lua腳本,因為它們只有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] 是日/小時關聯的key,ARGV[1]是上限值,ARGV[2]是過期時間,返回值則是當前計數值+1后的結果,(如果已經達到上限,則實際上不會計數)
b.自然日+自然小時
如前文提到的,兩個的結合實際上并不是單純的拼湊,需要處理回退邏輯
//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] 是天關聯生成的key, KEYS[2] 是小時關聯生成的key,ARGV[1]是天的上限值,ARGV[2]是小時的上限值,ARGV[3]是天的過期時間,ARGV[4]是小時的過期時間,返回值同上
這里給的是比較粗糙的寫法,主要需要表達的就是,進行兩個條件判斷時,有其中一個不滿足,另一個都需要進行回退.
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 = "@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....
使用注解之后的寫法:
//簡化版代碼
@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
}
}
感謝各位的閱讀,以上就是“怎么使用Java編寫一個簡單的風控組件”的內容了,經過本文的學習后,相信大家對怎么使用Java編寫一個簡單的風控組件這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。