# 6.3 Mongo

# 6.3.1 第三方库

# 6.3.2 配置参数

名称 类型 描述
dsn string 连接串

# 6.3.3 示例代码

以下完整示例详见:third-mongo-example (opens new window)

  1. 组件封装

文件位置:third-mongo-example/mongo/mongo.go (opens new window)

package mongo

import (
	"context"
	"fmt"
	"log"

	"github.com/dobyte/due/v2/core/pool"
	"github.com/dobyte/due/v2/etc"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var factory = pool.NewFactory(func(name string) (*Client, error) {
	return NewInstance(fmt.Sprintf("etc.mongo.%s", name))
})

type (
	Client = mongo.Client
)

type Config struct {
	DSN string `json:"dsn"` // 连接串
}

// Instance 获取实例
func Instance(name ...string) *Client {
	var (
		err error
		ins *Client
	)

	if len(name) == 0 {
		ins, err = factory.Get("default")
	} else {
		ins, err = factory.Get(name[0])
	}

	if err != nil {
		log.Fatalf("create mongo instance failed: %v", err)
	}

	return ins
}

// NewInstance 新建实例
func NewInstance[T string | Config | *Config](config T) (*Client, error) {
	var (
		conf *Config
		v    any = config
		ctx      = context.Background()
	)

	switch c := v.(type) {
	case string:
		conf = &Config{DSN: etc.Get(fmt.Sprintf("%s.dsn", c)).String()}
	case Config:
		conf = &c
	case *Config:
		conf = c
	}

	opts := options.Client().ApplyURI(conf.DSN)

	client, err := mongo.Connect(ctx, opts)
	if err != nil {
		return nil, err
	}

	return client, nil
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
  1. 配置示例

文件位置:third-mongo-example/etc/etc.toml (opens new window)

[mongo.default]
    # 连接串
    dsn = "mongodb://root:12345678@127.0.0.1:27017"
1
2
3
  1. 组件调用

文件位置:third-mongo-example/main.go (opens new window)

package main

import (
	"context"
	"third-mongo-example/mongo"

	"github.com/dobyte/due/v2/log"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
	client := mongo.Instance("default")

	if err := client.Ping(context.Background(), readpref.Primary()); err != nil {
		log.Errorf("mongo connection error: %v", err)
	} else {
		log.Infof("mongo connection success")
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19