使用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.