Golang连接MongoDB时SRV记录无法解析的解决方法

Golang连接MongoDB时SRV记录无法解析的解决方法 你好,

我无法使用SRV协议连接MongoDB,请帮助我建立连接。

我的代码:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
    domain := "mongodb+srv://USERNAME:PASSWORD@cluster1.gdbmd.mongodb.net/my_docker_db?retryWrites=true&w=majority"
    fmt.Println(domain)
    client, err := mongo.NewClient(options.Client().ApplyURI(domain))
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("No Error")
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)
    err = client.Ping(ctx, readpref.Primary())
    if err != nil {
        log.Fatal(err)
    }
    databases, err := client.ListDatabaseNames(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(databases)
}

错误: 解析URI时出错:在127.0.0.53:53上查找cluster1.gdbmd.mongodb.net时失败:无法解析DNS消息

谢谢。


更多关于Golang连接MongoDB时SRV记录无法解析的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang连接MongoDB时SRV记录无法解析的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


问题出现在DNS解析上,具体是SRV记录解析失败。这通常是由于DNS服务器配置或网络环境问题导致的。以下是几种解决方法:

方法1:使用 tls=true 参数

domain := "mongodb+srv://USERNAME:PASSWORD@cluster1.gdbmd.mongodb.net/my_docker_db?retryWrites=true&w=majority&tls=true"

方法2:指定DNS解析器

package main

import (
    "context"
    "fmt"
    "log"
    "net"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
    // 自定义DNS解析器
    dialer := &net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
    }
    
    customResolver := &net.Resolver{
        PreferGo: true,
        Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
            return dialer.DialContext(ctx, "udp", "8.8.8.8:53")
        },
    }
    
    domain := "mongodb+srv://USERNAME:PASSWORD@cluster1.gdbmd.mongodb.net/my_docker_db?retryWrites=true&w=majority"
    
    clientOptions := options.Client().
        ApplyURI(domain).
        SetDialer(&mongo.DefaultDialer{
            Dialer: &net.Dialer{
                Timeout:   30 * time.Second,
                KeepAlive: 30 * time.Second,
                Resolver:  customResolver,
            },
        })
    
    client, err := mongo.NewClient(clientOptions)
    if err != nil {
        log.Fatal(err)
    }
    
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)
    
    err = client.Ping(ctx, readpref.Primary())
    if err != nil {
        log.Fatal(err)
    }
    
    databases, err := client.ListDatabaseNames(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(databases)
}

方法3:使用标准连接字符串(非SRV)

// 从MongoDB Atlas获取标准连接字符串
domain := "mongodb://cluster1-shard-00-00.gdbmd.mongodb.net:27017,cluster1-shard-00-01.gdbmd.mongodb.net:27017,cluster1-shard-00-02.gdbmd.mongodb.net:27017/my_docker_db?ssl=true&replicaSet=atlas-xxxxxx-shard-0&authSource=admin&retryWrites=true&w=majority"

方法4:检查网络连接和DNS配置

package main

import (
    "context"
    "fmt"
    "net"
    "time"
)

func checkDNS() {
    resolver := &net.Resolver{
        PreferGo: true,
    }
    
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    // 测试DNS解析
    addrs, err := resolver.LookupSRV(ctx, "mongodb", "tcp", "cluster1.gdbmd.mongodb.net")
    if err != nil {
        fmt.Printf("SRV解析失败: %v\n", err)
        
        // 尝试A记录解析
        ips, err := resolver.LookupHost(ctx, "cluster1.gdbmd.mongodb.net")
        if err != nil {
            fmt.Printf("A记录解析失败: %v\n", err)
        } else {
            fmt.Printf("A记录解析成功: %v\n", ips)
        }
    } else {
        fmt.Printf("SRV记录: %v\n", addrs)
    }
}

func main() {
    checkDNS()
}

方法5:更新驱动版本

go get -u go.mongodb.org/mongo-driver/mongo

最常见的问题是DNS服务器不支持SRV记录解析。方法2通过指定Google的公共DNS(8.8.8.8)可以解决大多数DNS解析问题。如果问题仍然存在,使用方法3的标准连接字符串是最可靠的替代方案。

回到顶部