作者: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
//简化版代码@Componentclass DetectManager {    fun matchExceptionally(eventId: String, content: String){        //调用规定匹配        val rt = ruleService.match(eventId,content)        if (!rt) {            throw BaseException(ErrorCode.OPERATION_TOO_FREQUENT)        }    }}

在service中调用该办法

//简化版代码@Serviceclass 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@Componentclass 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()    }}

须要将参数放入到上下文中,并起名为arg1arg2....

四、测试一下

1.写法

应用注解之后的写法:

//简化版代码@Serviceclass 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开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞+转发哦!