天天看點

風控系統就該這麼設計(萬能通用)

風控系統就該這麼設計(萬能通用)

一、背景

1.為什麼要做風控?

風控系統就該這麼設計(萬能通用)

這不得拜産品大佬所賜

目前我們業務有使用到非常多的AI能力,如ocr識别、語音測評等,這些能力往往都比較費錢或者費資源,是以在産品層面也希望我們對使用者的能力使用次數做一定的限制,是以風控是必須的!

2.為什麼要自己寫風控?

那麼多開源的風控元件,為什麼還要寫呢?是不是想重複發明輪子呀.

風控系統就該這麼設計(萬能通用)

要想回答這個問題,需要先解釋下我們業務需要用到的風控(簡稱業務風控),與開源常見的風控(簡稱普通風控)有何差別:

風控系統就該這麼設計(萬能通用)

是以,直接使用開源的普通風控,一般情況下是無法滿足需求的

3.其它要求

支援實時調整限制

很多限制值在首次設定的時候,基本上都是拍定的一個值,後續需要調整的可能性是比較大的,是以可調整并實時生效是必須的

二、思路

要實作一個簡單的業務風控元件,要做什麼工作呢?

1.風控規則的實作

a.需要實作的規則:

  • 自然日計數
  • 自然小時計數
  • 自然日+自然小時計數
自然日+自然小時計數 這裡并不能單純地串聯兩個判斷,因為如果自然日的判定通過,而自然小時的判定不通過的時候,需要回退,自然日跟自然小時都不能計入本次調用!

b.計數方式的選擇:

目前能想到的會有:

  • mysql+db事務 持久化、記錄可溯源、實作起來比較麻煩,稍微“重”了一點
  • redis+lua 實作簡單,redis的可執行lua腳本的特性也能滿足對“事務”的要求
  • mysql/redis+分布式事務 需要上鎖,實作複雜,能做到比較精确的計數,也就是真正等到代碼塊執行成功之後,再去操作計數
目前沒有很精确技術的要求,代價太大,也沒有持久化的需求,是以選用 redis+lua 即可

2.調用方式的實作

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

三、具體實作

1.風控計數規則實作

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]是小時的過期時間,傳回值同上

這裡給的是比較粗糙的寫法,主要需要表達的就是,進行兩個條件判斷時,有其中一個不滿足,另一個都需要進行回退.

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 = "@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看看

風控系統就該這麼設計(萬能通用)
  • 注解值擷取成功
  • 表達式解析成功