关于前端:为什么要做风控

5次阅读

共计 4367 个字符,预计需要花费 11 分钟才能阅读完成。

这不得拜产品大佬所赐

目前咱们业务有应用到十分多的 AI 能力, 如 ocr 辨认、语音测评等, 这些能力往往都比拟费钱或者费资源, 所以在产品层面也心愿咱们对用户的能力应用次数做肯定的限度, 因而风控是必须的!
2. 为什么要本人写风控?
那么多开源的风控组件, 为什么还要写呢? 是不是想反复创造轮子呀.

要想答复这个问题, 须要先解释下咱们业务须要用到的风控 (简称业务风控), 与开源常见的风控(简称一般风控) 有何区别:

风控类型目标对象规定业务风控实现产品定义的一些限度, 达到限度时, 有具体的业务流程, 如充值 vip 等比拟复杂多变的, 例如针对用户进行风控, 也能针对用户 + 年级进行风控天然日、天然小时等一般风控爱护服务或数据, 拦挡异样申请等接口、局部能够加上简略参数个别用得更多的是滑动窗口
因而, 间接应用开源的一般风控, 个别状况下是无奈满足需要的
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 看看

注解值获取胜利
表达式解析胜利

正文完
 0