欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Java編寫一個簡單的風控組件

 更新時間:2022年12月31日 09:27:44   作者:wingli  
這篇文章主要為大家詳細介紹了如何基于Java編寫一個簡單的風控組件,文中的示例代碼講解詳細,對我們學習Java有一定的幫助,需要的可以參考一下

一、背景

1.為什么要做風控

這不得拜產(chǎn)品大佬所賜

目前我們業(yè)務(wù)有使用到非常多的AI能力,如ocr識別、語音測評等,這些能力往往都比較費錢或者費資源,所以在產(chǎn)品層面也希望我們對用戶的能力使用次數(shù)做一定的限制,因此風控是必須的!

2.為什么要自己寫風控

那么多開源的風控組件,為什么還要寫呢?是不是想重復發(fā)明輪子呀.

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

風控類型目的對象規(guī)則
業(yè)務(wù)風控實現(xiàn)產(chǎn)品定義的一些限制,達到限制時,有具體的業(yè)務(wù)流程,如充值vip等比較復雜多變的,例如針對用戶進行風控,也能針對用戶+年級進行風控自然日、自然小時等
普通風控保護服務(wù)或數(shù)據(jù),攔截異常請求等接口、部分可以加上簡單參數(shù)一般用得更多的是滑動窗口

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

3.其它要求

支持實時調(diào)整限制

很多限制值在首次設(shè)置的時候,基本上都是拍定的一個值,后續(xù)需要調(diào)整的可能性是比較大的,因此可調(diào)整并實時生效是必須的

二、思路

要實現(xiàn)一個簡單的業(yè)務(wù)風控組件,要做什么工作呢?

1.風控規(guī)則的實現(xiàn)

a.需要實現(xiàn)的規(guī)則

  • 自然日計數(shù)
  • 自然小時計數(shù)
  • 自然日+自然小時計數(shù)

自然日+自然小時計數(shù) 這里并不能單純地串聯(lián)兩個判斷,因為如果自然日的判定通過,而自然小時的判定不通過的時候,需要回退,自然日跟自然小時都不能計入本次調(diào)用!

b.計數(shù)方式的選擇

目前能想到的會有:

mysql+db事務(wù)

  • 持久化、記錄可溯源、實現(xiàn)起來比較麻煩,稍微“”了一點
  • redis+lua
  • 實現(xiàn)簡單,redis的可執(zhí)行l(wèi)ua腳本的特性也能滿足對“事務(wù)”的要求
  • mysql/redis+分布式事務(wù)
  • 需要上鎖,實現(xiàn)復雜,能做到比較精確的計數(shù),也就是真正等到代碼塊執(zhí)行成功之后,再去操作計數(shù)

目前沒有很精確技術(shù)的要求,代價太大,也沒有持久化的需求,因此選用 redis+lua 即可

2.調(diào)用方式的實現(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)雅一點的方法呢? 用注解可能會更好一點(也比較有爭議其實,這邊先支持實現(xiàn))

由于傳入的 content 是跟業(yè)務(wù)關(guān)聯(lián)的,所以需要通過Spel來將參數(shù)構(gòu)成對應(yīng)的content

三、具體實現(xiàn)

1.風控計數(shù)規(guī)則實現(xiàn)

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] 是日/小時關(guān)聯(lián)的key,ARGV[1]是上限值,ARGV[2]是過期時間,返回值則是當前計數(shù)值+1后的結(jié)果,(如果已經(jīng)達到上限,則實際上不會計數(shù))

b.自然日+自然小時

如前文提到的,兩個的結(jié)合實際上并不是單純的拼湊,需要處理回退邏輯

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

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

2.注解的實現(xiàn)

a.定義一個@Detect注解

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class Detect(

    /**
     * 事件id
     */
    val eventId: String = "",

    /**
     * content的表達式
     */
    val contentSpel: String = ""

)

其中content是需要經(jīng)過表達式解析出來的,所以接受的是個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)換表達式
        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ù)放入到上下文中,并起名為arg1arg2....

四、測試一下

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看看

  • 注解值獲取成功
  • 表達式解析成功

以上就是基于Java編寫一個簡單的風控組件的詳細內(nèi)容,更多關(guān)于Java風控組件的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論