温馨提示×

centos redis限速怎么配置

小樊
51
2026-09-18 00:35:13
栏目: 云计算

在 CentOS 上给 Redis 做“限速”(限流/限制访问频率),常见有几种做法,取决于你想限制什么:


一、限制 Redis 自身资源(CPU / 内存 / 连接数)

1️⃣ 限制最大连接数(常用)

编辑 Redis 配置文件:

vi /etc/redis.conf

修改或添加:

maxclients 1000

超过该连接数,新连接会被拒绝

重启 Redis:

systemctl restart redis

2️⃣ 限制内存使用(防止被打爆)

maxmemory 2gb
maxmemory-policy allkeys-lru

二、限制客户端请求速率(真正的“限速”)

Redis 原生不支持 QPS 限速,一般通过 应用层或中间件 实现。

✅ 方式一:Redis + Lua 脚本(令牌桶 / 计数器)

示例:限制某 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

✅ 方式二:使用 Redis + 应用代码(推荐)

Java(Spring Boot)示例

if (redisTemplate.opsForValue().increment("rate:ip", 1) > 10) {
    throw new RuntimeException("请求过于频繁");
}
redisTemplate.expire("rate:ip", 1, TimeUnit.SECONDS);

三、网络层限速(CentOS 层面)

✅ 方式一:iptables 限制连接频率

iptables -A INPUT -p tcp --dport 6379 -m limit --limit 100/minute -j ACCEPT
iptables -A INPUT -p tcp --dport 6379 -j DROP

✅ 方式二:firewalld + rich rule(CentOS 7+)

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)

如果你能说清楚:

  • 是 限制 QPS / 连接数 / IP
  • Redis 版本
  • 是否公网

我可以给你更精确的配置示例。

0 踩