利用Lua脚本限制用户的访问频率

常见于防止刷接口、限流等场景。它通过 Redis 实现了一个基于时间窗口的访问频率控制机制。

🛡️ 应用场景:

短链服务访问频率控制

接口防刷(如登录、注册、短信发送)

防止爬虫/机器人高频访问

控制 API 调用频率(简易限流)
📌 脚本功能详解:

java 复制代码
-- 设置用户访问频率限制的参数
local username = KEYS[1]                     -- 用户标识(例如用户ID或IP)
local timeWindow = tonumber(ARGV[1])         -- 时间窗口,单位:秒

-- 构造 Redis 中存储用户访问次数的键名
local accessKey = "short-link:user-flow-risk-control:" .. username

-- 原子递增访问次数,并获取递增后的值
local currentAccessCount = redis.call("INCR", accessKey)

-- 设置键的过期时间
if currentAccessCount == 1 then
    redis.call("EXPIRE", accessKey, timeWindow)
end

-- 返回当前访问次数
return currentAccessCount

功能说明:

INCR 是原子操作,确保并发下计数准确。

第一次访问时(即 currentAccessCount == 1),设置一个过期时间 timeWindow,这样该时间窗口之后自动清零。

如果超过某个阈值(比如返回值 > N),服务端可以决定拒绝请求或进行风控处理。

🔧 使用方式(示例):

在 Redis 客户端中调用此脚本的方式如下(以 Redis CLI 为例):

java 复制代码
@Slf4j
@RequiredArgsConstructor
public class UserFlowRiskControlFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;
    private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;

    private static final String USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH = "lua/user_flow_risk_control.lua";

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH)));
        redisScript.setResultType(Long.class);
        String username = Optional.ofNullable(UserContext.getUsername()).orElse("other");
        Long result;
        try {
            result = stringRedisTemplate.execute(redisScript, Lists.newArrayList(username), userFlowRiskControlConfiguration.getTimeWindow());
        } catch (Throwable ex) {
            log.error("执行用户请求流量限制LUA脚本出错", ex);
            returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
            return;
        }
        if (result == null || result > userFlowRiskControlConfiguration.getMaxAccessCount()) {
            returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
            return;
        }
        filterChain.doFilter(request, response);
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        }
    }
}
相关推荐
啟明起鸣17 分钟前
【数据结构】B 树——高度近似可”独木成林“的榕树——详细解说与其 C 代码实现
c语言·开发语言·数据结构
十八旬38 分钟前
苍穹外卖项目实战(日记十)-记录实战教程及问题的解决方法-(day3-2)新增菜品功能完整版
java·开发语言·spring boot·mysql·idea·苍穹外卖
这周也會开心1 小时前
Java-多态
java·开发语言
Forward♞1 小时前
Qt——网络通信(UDP/TCP/HTTP)
开发语言·c++·qt
XH华1 小时前
C语言第十三章自定义类型:联合和枚举
c语言·开发语言
2401_858286112 小时前
OS26.【Linux】进程程序替换(下)
linux·运维·服务器·开发语言·算法·exec·进程
草莓熊Lotso2 小时前
【C语言强化训练16天】--从基础到进阶的蜕变之旅:Day13
c语言·开发语言·刷题·强化训练
一尘之中3 小时前
在Python 2.7中安装SQLAlchemy的完整指南
开发语言·python·ai写作
黄贵根3 小时前
使用JDK11标准 实现 图数据结构的增删查改遍历 可视化程序
java·开发语言·数据结构
电商数据girl3 小时前
Python 爬虫获得淘宝商品详情 数据【淘宝商品API】
大数据·开发语言·人工智能·爬虫·python·json·php