使用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;
    }
}
相关推荐
紫幽35 分钟前
从 0 用 Vue 做屏并生成 LVGL 单片机代码(完整源码备忘)
前端·单片机
郭邯38 分钟前
用 AI 辅助开发一个文件大小转换工具:从需求到上线的完整过程
前端
勾勾圈圈蛋蛋40 分钟前
前中台项目
前端
触底反弹44 分钟前
🔐 前端鉴权不再难!手把手带你搞懂 JWT + Zustand + Axios 的完整登录方案
前端·axios
打呵欠的猫1 小时前
我用 AI 写了一个"需求翻译器",产品的 PRD 直接变成开发任务清单
前端·ai编程
fatcoder1 小时前
玩转Nginx 09 — 运维排障:三场"火灾"实战演练
前端·后端·nginx
前端玩坑坑1 小时前
View Transitions API 入门教程,优雅过度
前端
李高钢2 小时前
WPF MVVM Light(三):RelayCommand 命令与 Messenger 消息
前端·c#·wpf
lichenyang4532 小时前
Socket.IO 原理与技术选型
前端
qq21084629532 小时前
在python中什么是 self 和 cls?
开发语言·前端·python