Go应用连接MongoDB遇ReplicaSetNoPrimary错误求助
Go连接MongoDB出现ReplicaSetNoPrimary错误的排查与解决
我在使用Go应用连接MongoDB时遇到了ReplicaSetNoPrimary错误,相关配置、代码及报错信息如下:
示例MongoDB URI
mongodb+srv://user:pass@ntw.55n9jaw.mongodb.net/?retryWrites=true&w=majority&appName=ntw
连接代码
func SetupDB(uri string) *mongo.Client { log.Printf("Connecting to MongoDB") log.Printf("URI: %s", uri) ctx := context.TODO() client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) if err != nil { log.Fatalf("Failed to connect to MongoDB: %v", err) } defer func() { if err := client.Disconnect(ctx); err != nil { log.Fatalf("Failed to disconnect from MongoDB: %v", err) } }() if err := client.Ping(ctx, readpref.Primary()); err != nil { log.Fatalf("Failed to ping MongoDB: %v", err) } log.Printf("Connected to MongoDB") return client }
报错信息(中文翻译)
Ping MongoDB失败:服务器选择错误:服务器选择超时,当前拓扑结构: { 类型: ReplicaSetNoPrimary, 服务器: [{ 地址: ac-l4ofxbw-shard-00-00.55n9jaw.mongodb.net:27017, 类型: 未知, 最后错误: tls: 证书验证失败: x509: 证书已过期或尚未生效: }, { 地址: ac-l4ofxbw-shard-00-01.55n9jaw.mongodb.net:27017, 类型: 未知, 最后错误: tls: 证书验证失败: x509: 证书已过期或尚未生效: }, { 地址: ac-l4ofxbw-shard-00-02.55n9jaw.mongodb.net:27017, 类型: 未知, 最后错误: tls: 证书验证失败: x509: 证书已过期或尚未生效: }, ] }
排查与解决步骤
- 校准系统时间:报错核心是x509证书验证失败,最常见原因是本地系统时间与MongoDB服务器时间偏差过大。开启系统自动时间同步,确保时间准确。
- 更新MongoDB Go驱动:旧版本驱动可能存在证书兼容性问题,执行命令更新到最新版:
go get go.mongodb.org/mongo-driver/mongo@latest - 检查证书状态:如果是自建MongoDB集群,确认SSL证书是否过期,及时重新生成有效证书;若是MongoDB Atlas服务,官方证书通常不会过期,优先排查本地时间。
- 调整连接配置:临时调整读取偏好测试连接(生产环境建议保持Primary),修改Ping代码如下:
if err := client.Ping(ctx, readpref.SecondaryPreferred()); err != nil { log.Fatalf("Failed to ping MongoDB: %v", err) } - 验证网络连通性:确认应用所在服务器能访问MongoDB集群所有节点的27017端口,检查防火墙、安全组是否拦截流量。
内容的提问来源于stack exchange,提问作者user16073989
相关产品推荐
相关产品推荐

