> ## Content Index
> Fetch the complete content index at: https://zyx322.xyz/llms.txt
> Use this file to discover other available public pages before exploring further.

# Redis 从 0 到 1（二）：Go 连 Redis 半夜总报 EOF？连接池 5 参数与 redisx 封装
- URL: https://zyx322.xyz/csdn-2026-10-10-980733a8c1ac/
- Published: 2026-10-10T04:00:00.000Z
- Updated: 2026-11-26T07:02:11.000Z
- Author: ZYX
- Tags: redis

> 上一篇《Redis 从 0 到 1（一）：安装环境配置 Redis——3 种方式跑通 + 10 项配置 + Go 第一个 PING》我们用 3 种方式装好了 Redis 7，并用 Go 发出了第一个 PING，链接：[https://blog.csdn.net/2501\_92769340/article/details/167399349](https://blog.csdn.net/2501%5F92769340/article/details/167399349?ref=zyx322.xyz) 。 本篇解决下一个问题：把 `redis.NewClient` 默认参数直接搬上生产，为什么总在半夜低峰期批量报 EOF？

### 一、故障现象：白天正常，半夜批量 EOF

一个真实的现象：服务白天几千 QPS 稳如老狗，凌晨三四点低峰期反而批量报 `EOF` 或 `read: connection reset by peer`，过几分钟自己恢复。

根因链条是这样的：go-redis 默认 `PoolSize = 10 × GOMAXPROCS`，池子里的空闲连接默认**不会被主动清理**，但服务端 redis.conf 里 `timeout 300`（5 分钟）会把空闲连接单方面断开。半夜流量低，连接在池里闲置超过 300 秒被服务端悄悄 kill；早上一来请求，客户端拿到一个"尸体连接"，一读写就是 EOF。

这不是 bug，是**客户端池参数与服务端空闲超时不匹配**。解决它只需要把 5 个参数配对。

### 二、连接池 5 个关键参数

| 参数              | 默认值      | 作用      | 建议                             |
| --------------- | -------- | ------- | ------------------------------ |
| PoolSize        | 10×CPU 核 | 池最大连接数  | 按 QPS × 单命令耗时(秒) 估算，常见 20\~100 |
| MinIdleConns    | 0        | 保底空闲连接  | 设 PoolSize 的 1/4，避免高峰现建连接      |
| MaxIdleConns    | 0（不限制）   | 空闲连接上限  | 低峰期释放多余连接，建议 ≈ PoolSize/2      |
| ConnMaxIdleTime | 30min    | 空闲多久主动关 | **必须小于服务端 timeout**，如 60s      |
| ConnMaxLifetime | 0（不限制）   | 连接最大寿命  | 30min\~1h，防 NAT/LB 静默断连        |

配平规则一句话：**客户端主动关连接的速度，要比服务端 kill 得快**。服务端 `timeout 300`，客户端 `ConnMaxIdleTime` 设 60\~120 秒，尸体连接就不再出现。

### 三、Go 实操：redisx 封装（全系列复用，收藏点 1）

下面这个 `redisx` 包是整个系列后面 35 篇共用的入口，一次写好：

```go
// redisx/redisx.go
package redisx

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

// Config 连接配置，只暴露需要调的参数
type Config struct {
	Addr         string
	Password     string
	DB           int
	PoolSize     int
	MinIdleConns int
}

// NewClient 创建带池化管理、超时、重试、健康检查的客户端
func NewClient(cfg Config) (*redis.Client, error) {
	rdb := redis.NewClient(&redis.Options{
		Addr:     cfg.Addr,
		Password: cfg.Password,
		DB:       cfg.DB,

		// —— 池化：与服务端 timeout 配平，杜绝尸体连接 ——
		PoolSize:        cfg.PoolSize,
		MinIdleConns:    cfg.MinIdleConns,
		MaxIdleConns:    cfg.PoolSize / 2,
		ConnMaxIdleTime: 90 * time.Second, // < 服务端 timeout 300
		ConnMaxLifetime: 30 * time.Minute,

		// —— 超时：任何一次调用都不许无限等 ——
		DialTimeout:  3 * time.Second,
		ReadTimeout:  2 * time.Second,
		WriteTimeout: 2 * time.Second,
		PoolTimeout:  3 * time.Second, // 从池里取连接的最长等待

		// —— 重试：只对幂等读有意义，写操作重试要谨慎（第 28 篇细讲）——
		MaxRetries:      2,
		MinRetryBackoff: 100 * time.Millisecond,
		MaxRetryBackoff: 1 * time.Second,
	})

	// 启动即健康检查，失败直接返回错误，不让坏客户端流窜到业务里
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	if err := rdb.Ping(ctx).Err(); err != nil {
		return nil, fmt.Errorf("redis 健康检查失败: %w", err)
	}
	return rdb, nil
}

// PoolStats 暴露池指标，第 25/34 篇的排查会用到
func PoolStats(rdb *redis.Client) string {
	s := rdb.PoolStats()
	return fmt.Sprintf("hits=%d misses=%d timeouts=%d total=%d idle=%d stale=%d",
		s.Hits, s.Misses, s.Timeouts, s.TotalConns, s.IdleConns, s.StaleConns)
}

```

使用方（业务代码里就这么写）：

```go
package main

import (
	"context"
	"fmt"
	"time"

	"redis-0to1/redisx"
)

func main() {
	rdb, err := redisx.NewClient(redisx.Config{
		Addr: "127.0.0.1:6379", Password: "redis123",
		PoolSize: 20, MinIdleConns: 5,
	})
	if err != nil {
		panic(err)
	}
	defer rdb.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	if err := rdb.Set(ctx, "hello", "redis-0to1", time.Minute).Err(); err != nil {
		panic(fmt.Sprintf("SET 失败: %v", err))
	}
	val, err := rdb.Get(ctx, "hello").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println(val, "|", redisx.PoolStats(rdb))
}

```

### 四、为什么 EOF 常在半夜出现：三类断连场景对照

| 断连场景        | 触发方                | 时间特征    | 解法                        |
| ----------- | ------------------ | ------- | ------------------------- |
| 服务端空闲超时     | redis.conf timeout | 低峰期（半夜） | ConnMaxIdleTime < timeout |
| LB/NAT 静默断连 | 中间设备               | 长连接数小时后 | ConnMaxLifetime + 应用层心跳   |
| Redis 重启/切主 | 服务端                | 运维窗口    | 重试 + 哨兵客户端（第 9 篇）         |

### 五、命令与配置清单（收藏点 2）

| 命令/配置                 | 作用                           |
| --------------------- | ---------------------------- |
| CONFIG GET timeout    | 看服务端空闲断开秒数（0 = 不断开）          |
| CONFIG GET maxclients | 服务端连接上限（默认 10000）            |
| INFO clients          | 当前连接数、被拒绝连接数                 |
| CLIENT LIST           | 逐个看连接来源 IP 与空闲时长（第 34 篇核心武器） |
| CLIENT SETNAME        | 给连接起名，排查时一眼认出是哪个服务           |

给连接起名的好习惯，go-redis 里一行搞定：

```go
rdb.Do(context.Background(), "CLIENT", "SETNAME", "order-service-pod-1")

```

### 六、服务端配置建议

```conf
# redis.conf —— 与客户端配平的两项
timeout 300          # 空闲 300 秒断开（客户端 ConnMaxIdleTime 要比它小）
tcp-keepalive 60     # TCP 层保活，帮 NAT 环境续命
maxclients 10000     # 连接上限，第 34 篇会用到

```

### 七、总结

1. 半夜 EOF 的根因：服务端 `timeout` 杀空闲连接，客户端池却留着尸体；
2. 配平原则：`ConnMaxIdleTime` < 服务端 `timeout`，`ConnMaxLifetime` 防中间设备；
3. PoolSize 别拍脑袋：按 `QPS × 单命令耗时` 估算，第 25 篇给计算公式；
4. redisx 封装四件套：池化配平、超时兜底、有限重试、启动健康检查——全系列复用。

**下一篇预告**：连接稳了，该干活了——下一篇《五大结构 20 个最常用命令，用 Go 各写一个真实用法》，我们把 String/Hash/List/Set/ZSet 放进缓存对象、购物车、关注列表、排行榜 5 个真实场景里逐个过一遍。