使用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;
    }
}
相关推荐
gyx_这个杀手不太冷静16 小时前
Agent开发进阶指南(第 1 章):AI Agent 到底是什么?
前端·agent·ai编程
小小小小宇16 小时前
模型相关知识
前端
小小小小宇16 小时前
模型相关知识二
前端
IT_陈寒17 小时前
Python装饰器竟然偷偷改了函数名?这个坑我爬了三天
前端·人工智能·后端
Momo__17 小时前
Vite 8.1 打包开发模式——10000 组件冷启动 15 倍,"No Bundle Dev" 七年后被自己终结
前端·vue.js·vite
YHL17 小时前
🤖 Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·javascript·人工智能
Monki17 小时前
AI 规范式 UI 设计,一键批量出页,高效落地不翻车
前端
山河木马17 小时前
渲染管线-计算得到gl_FragColor(片元着色器)之后续GPU流程
前端·webgl·计算机图形学
不想说话的麋鹿17 小时前
「项目实战」我用 Codex + GPT-5.5 + Trellis "氛围编程",独立做了一个情侣厨房小程序
前端·agent·全栈
接着奏乐接着舞。19 小时前
【2026年7月最新】69道RAG面试题
前端·人工智能·后端·aigc·embedding·rag