Golang 连接 MongoDB使用连接池

可以免费试用 MongoDB ,500MB 平时做测试没有问题啦,连接数据库可能因为网络有点慢,但是我们是测试啊,不在乎这点吧~

 

这是怎么申请试用版的博客,感谢这位大佬。注册好用起来很方便~ 传送门 https://www.cnblogs.com/xybaby/p/9460634.html

 

连接数据库选择的驱动是 mongo-go-driver , 传送门 https://github.com/mongodb/mongo-go-driver/tree/master/examples/documentation_examples

 

具体操作是这样的,在GOPATH,或者项目目录下。

 

go get github.com/mongodb/mongo-go-driver/mongo

 

 如果用的是  Go Modules  引入后会爆红!所以我们需要 go mod tidy 。在国内你是知道的,所以我们这样。

 

powershell

$env:GOPROXY = "https://goproxy.io"

go mod tidy

 

然后下面是代码

建一个文件夹名字是 mgodb / mgo.go

package mgodb

import (
	"context"
	_"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

type mgo struct {
	uri string //数据库网络地址
	database string //要连接的数据库
	collection string //要连接的集合
}

func (m *mgo)Connect() *mongo.Collection {
	ctx , cancel :=context.WithTimeout(context.Background(),10*time.Second)
	defer cancel() //养成良好的习惯,在调用WithTimeout之后defer cancel() 
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(m.uri))
	if err != nil {
		log.Print(err)
	}
	collection := client.Database(m.database).Collection(m.collection)
	return collection
}

 

基本就是这样连接了,下面我们来测试耗时在哪。 在当前文件夹创建 mgodb / mgo_test.go  Goland会自动识别这是测试文件。代码

 

package mgodb

import (
	"fmt"
	"testing"
)

func TestMgo_Connect(t *testing.T) {
	var mgo = &mgo{
		"mongodb+srv://user:password@官网给你的.mongodb.net",
		"MainSite",
		"UsersM12",
	}
        
         mgo.Connect()
	//collection :=mgo.Connect()
	//fmt.Printf("%T\n",collection)
}

 

可以直接在 Goland 里执行,但是在控制台功能更多。

 

在这里我们需要用到 Graphviz 绘图软件 ,记得在环境变量配置一下。 传送门 : http://www.graphviz.org/ 

 

我们在命令行里执行测试文件

 

 go test -bench . -cpuprofile cpu.out

 

这样会生成可执行文件  mgodb.test.exe 和 cpu.out

 

 go tool pprof cpu.out

 

这时会有一个交互界面在里面输入 web

 

(pprof) web
(pprof) exit

 就可以打开这张图片,svg 不能上传,大概可以看出连接花费了630ms

 

  大概就是这样了,查询的语法都在 github那个传送门里,可以去看一下。

 

 

这是我现在使用的代码可以参考一下。

在 和 mgodb 文件夹下 建一个 initDB.go 文件

 

package models
import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type Database struct {
	Mongo  * mongo.Client
}


var DB *Database


//初始化
func Init() {
	DB = &Database{
		Mongo: SetConnect(),
	}
}
// 连接设置
func SetConnect() *mongo.Client{
	uri := "mongodb+srv://用户名:密码@官方给的.mongodb.net"
	ctx ,cancel := context.WithTimeout(context.Background(),10*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx,options.Client().ApplyURI(uri).SetMaxPoolSize(20)) // 连接池
	if err !=nil{
		fmt.Println(err)
	}
	return client
}

 

 

mgodb 里的 mgo.db 现在的代码是这样的 使用起来比较简单,删除和插入文档,只需要一个唯一匹配的键值对就可以了

 

 

package mgodb

import (
	"blog/models"
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"strconv"
	"time"
)

type mgo struct {
	database   string
	collection string
}

func NewMgo(database, collection string) *mgo {

	return &mgo{
		database,
		collection,
	}
}

// 查询单个
func (m *mgo) FindOne(key string, value interface{}) *mongo.SingleResult {
	client := models.DB.Mongo
	collection, _ := client.Database(m.database).Collection(m.collection).Clone()
	//collection.
	filter := bson.D{{key, value}}
	singleResult := collection.FindOne(context.TODO(), filter)
	return singleResult
}

//插入单个
func (m *mgo) InsertOne(value interface{}) *mongo.InsertOneResult {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	insertResult, err := collection.InsertOne(context.TODO(), value)
	if err != nil {
		fmt.Println(err)
	}
	return insertResult
}

//查询集合里有多少数据
func (m *mgo) CollectionCount() (string, int64) {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	name := collection.Name()
	size, _ := collection.EstimatedDocumentCount(context.TODO())
	return name, size
}

//按选项查询集合 Skip 跳过 Limit 读取数量 sort 1 ,-1 . 1 为最初时间读取 , -1 为最新时间读取
func (m *mgo) CollectionDocuments(Skip, Limit int64, sort int) *mongo.Cursor {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	SORT := bson.D{{"_id", sort}} //filter := bson.D{{key,value}}
	filter := bson.D{{}}
	findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
	//findOptions.SetLimit(i)
	temp, _ := collection.Find(context.Background(), filter, findOptions)
	return temp
}

//获取集合创建时间和编号
func (m *mgo) ParsingId(result string) (time.Time, uint64) {
	temp1 := result[:8]
	timestamp, _ := strconv.ParseInt(temp1, 16, 64)
	dateTime := time.Unix(timestamp, 0) //这是截获情报时间 时间格式 2019-04-24 09:23:39 +0800 CST
	temp2 := result[18:]
	count, _ := strconv.ParseUint(temp2, 16, 64) //截获情报的编号
	return dateTime, count
}

//删除文章和查询文章
func (m *mgo) DeleteAndFind(key string, value interface{}) (int64, *mongo.SingleResult) {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	filter := bson.D{{key, value}}
	singleResult := collection.FindOne(context.TODO(), filter)
	DeleteResult, err := collection.DeleteOne(context.TODO(), filter, nil)
	if err != nil {
		fmt.Println("删除时出现错误,你删不掉的~")
	}
	return DeleteResult.DeletedCount, singleResult
}

//删除文章
func (m *mgo) Delete(key string, value interface{}) int64 {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	filter := bson.D{{key, value}}
	count, err := collection.DeleteOne(context.TODO(), filter, nil)
	if err != nil {
		fmt.Println(err)
	}
	return count.DeletedCount

}

//删除多个
func (m *mgo) DeleteMany(key string, value interface{}) int64 {
	client := models.DB.Mongo
	collection := client.Database(m.database).Collection(m.collection)
	filter := bson.D{{key, value}}

	count, err := collection.DeleteMany(context.TODO(), filter)
	if err != nil {
		fmt.Println(err)
	}
	return count.DeletedCount
}

 

 

应该知道怎么初始化吧

 文件结构是这样的,models 在根目录下

 

 

package main



func main() {
	models.Init() //初始化数据库
	app := newApp()
	routers.Router(app)         // 页面访问
	app.Run(iris.Addr(":3000")) // 火箭发射
}

 

posted @ 2019-04-18 20:03  州长在手  阅读(14926)  评论(0编辑  收藏  举报