使用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;
    }
}
相关推荐
ljt272496066112 分钟前
Vue笔记(十二)--mitt
前端·笔记
用户0333074139512 小时前
TypeScript using 与 AsyncDisposableStack:在真实服务端代码中协调多资源清理
前端
daisychey13 小时前
用 Playwright 做多平台内容分发,我踩过的 8 个坑
前端
IT_陈寒14 小时前
为什么你应该学习JavaScript?
前端·人工智能·后端
大龄秃头程序员14 小时前
iOS冷启动监控Demo
前端
光影少年14 小时前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法
掘金酱14 小时前
[稀土掘金 × 火山引擎] AI用量周榜冲刺赛|获奖名单公示
前端·人工智能·后端
泡泡oO15 小时前
“如果你还在用Superpowers,那我不要和你说话”
前端·后端·全栈
维克兜率天15 小时前
趋势过滤:避免被“假突破“反复打脸
前端
8年区块链老兵15 小时前
一篇文章教会你:用区块高度读懂比特币链上的每一笔交易
前端