应使用 github.com/redis/go-redis/v9;v8 及更早版本已归档,v9 强制要求非 nil context.Context,不传或传 nil 会直接 panic;连接前必须确认 redis-server 确实运行,macOS 用 brew services list | grep redis 或 redis-cli ping(返回 PONG 才通),Linux 用 systemctl status redis 或 ps aux | grep redis,Docker 容器连宿主需用 host.docker.internal:6379(Mac/Win)或 172.17.0.1:6379(Linux),远程服务器需检查 redis.conf 中 bind 为 0.0.0.0 且 protected-mode no(仅测试),Fiber 中应在 app.Use() 前全局初始化 rdb 并调用 rdb.Ping(ctx).Result() 验证连通性,Addr 不可省略,PoolSize 等参数建议显式设置,handler 中必须使用 c.Context() 而非 context.Background(),redis.Nil 是合法错误,需业务逻辑判断而非 panic。

别用 go-redis/redis/v8,现在唯一该用的是 github.com/redis/go-redis/v9;v8 及更早版本已归档,v9 强制要求 context.Context,不传或传 nil 会直接 panic。
确认 Redis 服务真在运行,再查 Go 代码
90% 的 connection refused 或超时,根本不是 Go 写错了——是 redis-server 没起来。
- macOS:跑
brew services list | grep redis,或直接redis-cli ping,返回PONG才算通 - Linux:用
systemctl status redis或ps aux | grep redis - Docker 容器里连宿主 Redis:
host.docker.internal:6379(Mac/Win),172.17.0.1:6379(Linux);写localhost:6379肯定失败 - 远程服务器:检查
redis.conf中bind是否仍为127.0.0.1(要改成0.0.0.0),且protected-mode no(仅测试环境)
Fiber 启动时初始化 Redis client 并验证连通性
Fiber 是 HTTP 框架,它本身不管理 Redis 生命周期,你得自己在 app.Use() 前完成连接和健康检查。别把 rdb 放进中间件闭包里反复 new,全局单例即可。
- 安装命令必须是:
go get github.com/redis/go-redis/v9 -
Addr字段不可省略或留空,不会 fallback 到 localhost - 初始化后必须调一次
rdb.Ping(ctx).Result(),这是唯一可靠的连通性验证方式 - 所有操作都要求非 nil
context.Context;HTTP handler 中建议用c.Context()继承请求生命周期 - 连接池参数建议显式设置:
PoolSize: 50、MinIdleConns: 5、IdleTimeout: 5 * time.Minute
import (
"context"
"time"
"github.com/gofiber/fiber/v2"
"github.com/redis/go-redis/v9"
)
<p>var rdb *redis.Client</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill11046" title="Sentinal Redis"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dbae7c507.jpg" alt="Sentinal Redis" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill11046" title="Sentinal Redis" class="overflowclass">Sentinal Redis</a>
<p class="overflowclass">监控Redis服务器健康状况、内存、性能及BullMQ队列。检查队列深度、失败任务,分析慢查询并诊断问题。</p>
</div>
<a rel="nofollow" href="/xiazai/skill11046" title="Sentinal Redis" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>func initRedis() {
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
PoolSize: 50,
MinIdleConns: 5,
IdleTimeout: 5 * time.Minute,
})</p><pre class="brush:php;toolbar:false;">ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_, err := rdb.Ping(ctx).Result()
if err != nil {
panic(err) // 不要静默忽略
}
}
在 Fiber handler 中安全使用 rdb.Get / rdb.Set
别在 handler 里用 context.Background(),必须用 c.Context() 控制超时与取消;同时注意 redis.Nil 是合法错误,不是异常,要显式判断。
-
rdb.Get(c.Context(), "user:123").Result()返回redis.Nil表示键不存在,不是网络错误 - 超时控制靠 context,不是 client 配置里的
ReadTimeout;设了也没用 - 批量读写优先用
rdb.MGet/rdb.MSet,避免 N+1 - 不要在每次 handler 中
defer rdb.Close()—— client 是全局复用的,关了就全断了
app.Get("/user/:id", func(c *fiber.Ctx) error {
key := "user:" + c.Params("id")
<pre class="brush:php;toolbar:false;">val, err := rdb.Get(c.Context(), key).Result()
if err == redis.Nil {
return c.Status(404).SendString("not found")
} else if err != nil {
return c.Status(500).SendString("redis error")
}
return c.SendString(val)
})
容易被忽略的三个点
v9 的 context 是硬性要求,但很多人只记得传,却忘了它直接影响超时行为;Docker 网络地址写错是高频坑;还有就是 redis.Nil 不等于普通 error,它不该打日志也不该 panic,而是业务逻辑分支的一部分。
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










