feizzer 2023-02-20 17:24 采纳率: 63.6%
浏览 27
已结题

go远程连接mongo失败

使用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.
  • 写回答

3条回答 默认 最新

  • MarkHan_ 2023-02-20 17:39
    关注

    这个错误可能是由于连接超时或无法正确连接到MongoDB服务器造成的。建议检查一下MongoDB服务器是否正常运行、IP地址和端口是否正确、服务器防火墙设置是否允许连接等。如果仍然无法解决问题,可以尝试增加连接选项中的超时时间或者将日志级别设置为调试模式,以获取更多详细的错误信息来排查问题。同时,可以考虑使用MongoDB官方提供的Go语言驱动程序来连接MongoDB,避免出现兼容性问题。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 2月28日
  • 已采纳回答 2月20日
  • 创建了问题 2月20日

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法