解决 Redis 报错 Write commands not allowed from read only
分析 Redis 在从库上执行包含写操作的 Lua 脚本报 ERR Write commands not allowed 根因,详解读写路由与主库对齐步骤。
问题现象
应用程序通过 EVAL 或 EVALSHA 执行 Lua 脚本时抛出异常:
redis.clients.jedis.exceptions.JedisDataException: ERR Write commands not allowed from a read-only replica.
脚本执行被中止。
触发根因
- 向从库(Replica)节点发送了包含写命令(如
redis.call('SET', ...))的 Lua 脚本:从库开启了replica-read-only yes,严禁在从库执行任何有写副作用的脚本。
诊断排查步骤
- 检查连接池路由配置: 确认执行该脚本的连接是否来源于只读连接池。
解决步骤与操作命令
步骤一:确保所有具备写操作的 Lua 脚本路由至 Master 节点
在应用层严格区分读写连接池,将所有包含写操作的 Lua 脚本(如分布式锁释放、滑动窗口限流)强制路由至主库执行。
步骤二:若为只读纯查询 Lua 脚本,使用 EVAL_RO(只读命令模式)
在 Redis 7.0+ 中,如果是只读脚本,使用只读命令执行:
EVAL_RO "return redis.call('GET', KEYS[1])" 1 my_key
验证方法
重新在主库节点执行测试:
redis-cli -h 10.0.0.1 -p 6379 EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 test_key hello
脚本顺利执行并返回 OK。


