使用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;
    }
}
相关推荐
AiMan2 分钟前
文心生成的内容能否下载吗?
前端
前端双越老师34 分钟前
程序员 1v1 访谈系列第十四期:接受焦虑 拥抱不确定
前端·ai编程·全栈
deli0071 小时前
MCP 协议 6 条消息拆开看:AI 为什么能自己读文件调接口
前端
风骏时光牛马2 小时前
请告诉我标题对应的内容、想要的风格,我马上给你生成。
前端
deli0072 小时前
OAuth 2.0 授权码流程实测:4 次跳转,少个 state 就被劫持
前端
deli0074 小时前
手机20%突然关机?电量百分比是估的,SOC曲线4组实测
前端
深蓝AI15 小时前
Meta 开源用了八年的设计系统 astryx:连坐两天 GitHub 总榜第一,组件库开始写给 agent 的说明书
前端·人工智能
IT_陈寒15 小时前
Vue的watch把我坑惨了,原来要这样用才靠谱
前端·人工智能·后端
1-1=016 小时前
Vue 3 模板语
前端·javascript·vue.js