在 CentOS 上给 Redis 做“限速”(限流/限制访问频率),常见有几种做法,取决于你想限制什么:
编辑 Redis 配置文件:
vi /etc/redis.conf
修改或添加:
maxclients 1000
超过该连接数,新连接会被拒绝
重启 Redis:
systemctl restart redis
maxmemory 2gb
maxmemory-policy allkeys-lru
Redis 原生不支持 QPS 限速,一般通过 应用层或中间件 实现。
示例:限制某 IP 每秒最多 10 次
-- rate_limit.lua
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local expire = tonumber(ARGV[2])
local current = redis.call('incr', key)
if current == 1 then
redis.call('expire', key, expire)
end
if current > limit then
return 0
else
return 1
end
调用示例:
redis-cli --eval rate_limit.lua ip:127.0.0.1 , 10 1
Java(Spring Boot)示例
if (redisTemplate.opsForValue().increment("rate:ip", 1) > 10) {
throw new RuntimeException("请求过于频繁");
}
redisTemplate.expire("rate:ip", 1, TimeUnit.SECONDS);
iptables -A INPUT -p tcp --dport 6379 -m limit --limit 100/minute -j ACCEPT
iptables -A INPUT -p tcp --dport 6379 -j DROP
firewall-cmd --add-rich-rule='rule port port=6379 protocol=tcp limit value=100/m accept'
Redis 默认不安全:
bind 127.0.0.1
protected-mode yes
requirepass yourpassword
| 场景 | 推荐方案 |
|---|---|
| 防刷接口 | Redis + Lua |
| 防连接风暴 | maxclients |
| 公网 Redis | 防火墙 + 密码 |
| 高并发系统 | 网关层限流(Nginx / Sentinel) |
如果你能说清楚:
我可以给你更精确的配置示例。