之前用 StackExchange.Redis,跑着跑着就断开连接,再也连不回来,只能重启应用。去 GitHub Issues 翻了一圈,踩坑的人一大堆。


abortConnect 默认是 true

这是最大的坑。连接断了之后不会自动重连,所有请求直接报 No connection is available to service this operation,一直报到你重启。

file

连接字符串加上 abortConnect=false 就好了:

localhost:6379,abortConnect=false

断了连不回来

就算加了 abortConnect=false,高负载下还是有可能断了就再也连不回来。Issue #168 里有人说自己写了个 wrapper 才解决的。

file

微软官方建议是自己写一个 ForceReconnect 方法,检测到 RedisConnectionException 的时候手动重建 ConnectionMultiplexer

Linux 上断线要等 15 分钟

Issue #1848,Linux 上 Redis 节点重启后客户端要等 15 分钟才重连。原因是内核参数 tcp_retries2 默认值太大,TCP 层一直在重试不肯放手。

file

改小就行:

sysctl -w net.ipv4.tcp_retries2=5

Docker 里改不了,要改宿主机的。

ConnectionMultiplexer 要复用

ConnectionMultiplexer 是设计成单例的,不能每次请求都 Connect() 一次,不然连接数直接爆炸。注册成单例就行:

services.AddSingleton<IConnectionMultiplexer>(
    ConnectionMultiplexer.Connect("localhost:6379,abortConnect=false"));