使用go远程连接mongo数据的时候发生了如下的错误:
2023/02/20 16:50:25 server selection error: server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: 114.55.101.215:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: connection(114.55.101.215:27017[-9]) incomplete read of message header: read tcp 26.26.26.1:62961->114.55.101.215:27017: wsarecv: An existing connection was forcibly closed by the remote host. }, ] }
连接mongo的golang代码如下:
func GetConnectClient() *mongo.Client {
// 设置客户端连接配置(connect=direct当数据库为集群时,可通过配置此项解决此驱动连接docker方式部署的mongodb集群由于docker方式部署的访问域名连接,而外面的网络访问不到的情况) mongodb://user:password@ip:port/database?connect=direct
// &replicaSet=集群名称 authSource=数据库名称 此配置也可以指定数据库
clientOptions := options.Client().ApplyURI("mongodb://xxx:27017/")
// 连接到MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// 检查连接
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
return client
}
mongo.conf文件的设置如下:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# Where and how to store data.
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
# engine:
# wiredTiger:
# how the process runs
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
timeZoneInfo: /usr/share/zoneinfo
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0 # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
这个错误可能是由于连接超时或无法正确连接到MongoDB服务器造成的。建议检查一下MongoDB服务器是否正常运行、IP地址和端口是否正确、服务器防火墙设置是否允许连接等。如果仍然无法解决问题,可以尝试增加连接选项中的超时时间或者将日志级别设置为调试模式,以获取更多详细的错误信息来排查问题。同时,可以考虑使用MongoDB官方提供的Go语言驱动程序来连接MongoDB,避免出现兼容性问题。
已经解决了 是防火墙阻断了。 屑!
不知道你这个问题是否已经解决, 如果还没有解决的话: