使用java springboot 使用 Redis 作为限流工具

使用 Redis 作为限流工具

Redis 还可以用于实现限流功能,例如限制每个 IP 地址的访问次数。你可以使用 Redis 的计数器功能来实现这一点。

实现限流逻辑
复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RateLimiter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public boolean isAllowed(String key, int maxRequests, int timeWindowInSeconds) {
        Long requestCount = redisTemplate.opsForValue().increment(key);

        if (requestCount == 1) {
            // 如果是第一次请求,设置过期时间
            redisTemplate.expire(key, timeWindowInSeconds, TimeUnit.SECONDS);
        }

        return requestCount <= maxRequests;
    }
}
相关推荐
代码老中医16 分钟前
逃离"Div汤":2026年,当AI写了75%的代码,前端开发者还剩什么?
前端
左夕19 分钟前
最基础的类型检测工具——typeof, instanceof
前端·javascript
yuki_uix20 分钟前
递归:别再"展开脑补"了,学会"信任"才是关键
前端·javascript
Moment3 小时前
腾讯终于对个人开放了,5 分钟在 QQ 里养一只「真能干活」的 AI 😍😍😍
前端·后端·github
比尔盖茨的大脑3 小时前
AI Agent 架构设计:从 ReAct 到 Multi-Agent 系统
前端·人工智能·全栈
天才熊猫君3 小时前
使用 Vite Mode 实现客户端与管理端的物理隔离
前端
HelloReader3 小时前
React Hook 到底是干嘛的?
前端
用户60572374873083 小时前
OpenSpec 实战:从需求到代码的完整工作流
前端·后端·程序员
寅时码4 小时前
React 正在演变为一场不可逆的赛博瘟疫:AI 投毒、编译器迷信与装死的官方
前端·react.js·设计模式