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")) // 火箭发射
}
Golang 连接 MongoDB使用连接池的更多相关文章
- golang mgo的mongo连接池设置:必须手动加上maxPoolSize
本司礼物系统使用了golang的 mongo库 mgo,中间踩了一些坑,总结下避免大家再踩坑 golang的mgo库说明里是说明了开启连接复用的,但观察实验发现,这并没有根本实现连接的控制,连接复用仅 ...
- java操作mongodb(连接池)(转)
原文链接: java操作mongodb(连接池) Mongo的实例其实就是一个数据库连接池,这个连接池里默认有10个链接.我们没有必要重新实现这个链接池,但是我们可以更改这个连接池的配置.因为Mong ...
- 在Spark中通过Scala + Mongodb实现连接池
How to implement connection pool in spark https://github.com/YulinGUO/BigDataTips/blob/master/spark/ ...
- [转载]MongoDB 标准连接字符串
MongoDB 标准连接字符串 mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[data ...
- Java程序中与MongoDB建立连接~小记
1.Mongo和MongoClient的关系 MongoClient继承自Mongo,使用Mongo也可建立连接,但是需要使用与Mongo适应的MongoOptions,MongoURI等类型. 2. ...
- 使用mongo-java-driver-3.0.2连接MongoDB数据库
这里使用的mongodb的java驱动版本是:3.0.2,文件名mongo-java-driver-3.0.2.jar 博客本地下载下载网址(也可以下载其它版本):http://central.ma ...
- node连接mongoDB篇
一般介绍: 由于mongodb数据库在javascript脚本环境中支持bson对象(json对象的二进制形式)的存取,因此对于数据的存取的效率是非常高的.在mongodb数据库中,将每一条等待插入的 ...
- MongoDB的连接字符串
本文导读:MongoDB数据库与传统的关系型数据库相比,它具有操作简单.完全免费.源码公开等特点,这使MongoDB产品广泛应用于各种大型门户网站和专业网站.由于MongoDB连接并不支持HTTP协议 ...
- 爬虫连接mongodb、多线程多进程的使用
一.连接mongodb 1. 设置数据库 client=pymongo.MongoClient(‘localhost’) 2. db=client[‘lag ...
随机推荐
- Elasticsearch之curl创建索引
前提,是 Elasticsearch之curl创建索引库 [hadoop@djt002 elasticsearch-2.4.3]$ curl -XPUT 'http://192.168.80.200: ...
- 2018网络预选赛 青岛 H
题目链接:https://pintia.cn/problem-sets/1036903825309761536/problems/1041156323504345088 题意:小明从某一点出发,向右方 ...
- IFC文档结构说明
工业基础类为代表的建筑信息BIM数据交换和共享在一个建筑或设施管理项目各参与者之间的开放规范的建模.IFC是国际openbim标准.本文件包含的IFC标准的规范.该规范包括的数据架构,表示为一个表达模 ...
- 【转】pecl,pear的不同
PEAR是PHP扩展与应用库(the PHP Extension and Application Repository)的缩写.它是一个PHP扩展及应用的一个代码仓库,基于php代码的,安装目录在/u ...
- Java-马士兵设计模式学习笔记-迭代器模式-模仿Collectin ArrayList LinckedList
Java Iterator模式 Java Iterator模式, 模仿Collectin ArrayList LinckedList 一.有如下几个类 1.接口Collection.java 2.接口 ...
- 1003 NOIP 模拟赛Day2 城市建设
题面不好找放一个吧. Description 描述 在有$N$个地级市的H省,政府为了城市开发建设,决定先修路,后造房子,以吸引外来人员.一开始每个城市中有$b_i$个住户,而在两个城市$u,v$之间 ...
- Luogu 4777 【模板】扩展中国剩余定理(EXCRT)
复习模板. 两两合并同余方程 $x\equiv C_{1} \ (Mod\ P_{1})$ $x\equiv C_{2} \ (Mod\ P_{2})$ 把它写成不定方程的形式: $x = C_{1} ...
- spark sql的应用场景
最近一直在银行做历史数据平台的项目,目前整个项目处于收尾的阶段,也好有时间整理下在项目中的一些收获. 该历史数据平台使用spark+Nosql架构了,Nosql提供了海量数据的实时查询,而spark提 ...
- iOS CocoaPods安装与使用
1.MAC安装Ruby环境 1> 安装RVM 控制台命令:$curl –L https://get.rvm.io | bash –s stable $source ~/.rvm/scripts ...
- 6678 emif norflash加载
终于搞定,纪念一下.CCS6很不好用,还是换回CCS5.5吧!