溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么使用Java編寫一個(gè)簡(jiǎn)單的風(fēng)控組件

發(fā)布時(shí)間:2023-01-03 10:01:48 來源:億速云 閱讀:102 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“怎么使用Java編寫一個(gè)簡(jiǎn)單的風(fēng)控組件”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么使用Java編寫一個(gè)簡(jiǎn)單的風(fēng)控組件”吧!

一、背景

1.為什么要做風(fēng)控

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

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

2.為什么要自己寫風(fēng)控

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

怎么使用Java編寫一個(gè)簡(jiǎn)單的風(fēng)控組件

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

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

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

3.其它要求

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

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

二、思路

要實(shí)現(xiàn)一個(gè)簡(jiǎn)單的業(yè)務(wù)風(fēng)控組件,要做什么工作呢?

1.風(fēng)控規(guī)則的實(shí)現(xiàn)

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

  • 自然日計(jì)數(shù)

  • 自然小時(shí)計(jì)數(shù)

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

自然日+自然小時(shí)計(jì)數(shù) 這里并不能單純地串聯(lián)兩個(gè)判斷,因?yàn)槿绻匀蝗盏呐卸ㄍㄟ^,而自然小時(shí)的判定不通過的時(shí)候,需要回退,自然日跟自然小時(shí)都不能計(jì)入本次調(diào)用!

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

目前能想到的會(huì)有:

mysql+db事務(wù)

  • 持久化、記錄可溯源、實(shí)現(xiàn)起來比較麻煩,稍微“”了一點(diǎn)

  • redis+lua

  • 實(shí)現(xiàn)簡(jiǎn)單,redis的可執(zhí)行l(wèi)ua腳本的特性也能滿足對(duì)“事務(wù)”的要求

  • mysql/redis+分布式事務(wù)

  • 需要上鎖,實(shí)現(xiàn)復(fù)雜,能做到比較精確的計(jì)數(shù),也就是真正等到代碼塊執(zhí)行成功之后,再去操作計(jì)數(shù)

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

2.調(diào)用方式的實(shí)現(xiàn)

a.常見的做法

先定義一個(gè)通用的入口

//簡(jiǎn)化版代碼

@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)用該方法

//簡(jiǎn)化版代碼

@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)的方法呢? 用注解可能會(huì)更好一點(diǎn)(也比較有爭(zhēng)議其實(shí),這邊先支持實(shí)現(xiàn))

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

三、具體實(shí)現(xiàn)

1.風(fēng)控計(jì)數(shù)規(guī)則實(shí)現(xiàn)

a.自然日/自然小時(shí)

自然日/自然小時(shí)可以共用一套lua腳本,因?yàn)樗鼈冎挥?code>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] 是日/小時(shí)關(guān)聯(lián)的key,ARGV[1]是上限值,ARGV[2]是過期時(shí)間,返回值則是當(dāng)前計(jì)數(shù)值+1后的結(jié)果,(如果已經(jīng)達(dá)到上限,則實(shí)際上不會(huì)計(jì)數(shù))

b.自然日+自然小時(shí)

如前文提到的,兩個(gè)的結(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] 是小時(shí)關(guān)聯(lián)生成的key,ARGV[1]是天的上限值,ARGV[2]是小時(shí)的上限值,ARGV[3]是天的過期時(shí)間,ARGV[4]是小時(shí)的過期時(shí)間,返回值同上

這里給的是比較粗糙的寫法,主要需要表達(dá)的就是,進(jìn)行兩個(gè)條件判斷時(shí),有其中一個(gè)不滿足,另一個(gè)都需要進(jìn)行回退.

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

a.定義一個(gè)@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á)式解析出來的,所以接受的是個(gè)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....

四、測(cè)試一下

1.寫法

使用注解之后的寫法:

//簡(jiǎn)化版代碼

@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編寫一個(gè)簡(jiǎn)單的風(fēng)控組件

感謝各位的閱讀,以上就是“怎么使用Java編寫一個(gè)簡(jiǎn)單的風(fēng)控組件”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)怎么使用Java編寫一個(gè)簡(jiǎn)單的風(fēng)控組件這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI