mongo

package module
v0.0.0-...-7c7313c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2019 License: MIT Imports: 12 Imported by: 0

README

mongo

mongo数据库连接池 适合高并发场景

采用双池设计,保证每次都能获取到

入门
安装
go get github.com/dollarkillerx/mongo
快速开始
    uri := "mongodb://127.0.0.1:27017"
	db, e := mongo.Open(uri)
	if e != nil {
		panic(e)
	}

	e = db.Ping()
	if e != nil {
		panic(e)
	}
	clog.Println("MongoDb 链接成功")

	// 配置
	db.SetMaxOpenConn(1) // 设置最大打开数量
	db.SetConnMaxLifetime(400 * time.Millisecond) // 设置超时时间

	database := db.Database("okp") // 设置数据库
	collection := database.Collection("BOOK") // 设置collection

	// 清空数据库和集合
	e = collection.Drop()

内部做了池化 效率提升

你可以使用我们提供的方法,也可以在池中获取 记得要放回蛤

对外暴露的接口 用完要记得放回
    uri := "mongodb://127.0.0.1:27017"
	db, e := mongo.Open(uri)
	if e != nil {
		panic(e)
	}

	e = db.Ping()
	if e != nil {
		panic(e)
	}
	clog.Println("MongoDb 链接成功")

	// 配置
	db.SetMaxOpenConn(1)
	db.SetConnMaxLifetime(400 * time.Millisecond)

	database := db.Database("okp")
	collection := database.Collection("BOOK")

	getCollection, pul, e := collection.GetCollection()
	if e == nil {
		defer func() {
			err := collection.PulCollection(pul)
			if err == nil {
				log.Println("放回成功")
			}
		}()
	}
	e = getCollection.Drop(context.TODO())
	if e == nil {
		log.Println("数据库清空成功200ok")
	}
简单CURL 操作

使用本插件提供的方法 都是自动从池中获取 和 放回

package main

import (
	"context"
	"github.com/dollarkillerx/mongo"
	"github.com/dollarkillerx/mongo/clog"
	"github.com/dollarkillerx/mongo/mongo-driver/bson"
	"github.com/dollarkillerx/mongo/mongo-driver/bson/primitive"
	"github.com/dollarkillerx/mongo/mongo-driver/mongo/options"
	"log"
	"time"
)

type Book struct {
	Id       primitive.ObjectID `bson:"_id"`
	Name     string
	Category string
	Weight   int
	Author   AuthorInfo
}

type AuthorInfo struct {
	Name    string
	Country string
}

const (
	categoryComputer = "计算机"
	categorySciFi    = "科幻"
	countryChina     = "中国"
	countryAmerica   = "美国"
)

var (
	books = []interface{}{
		&Book{
			Id:       primitive.NewObjectID(),
			Name:     "深入理解计算机操作系统",
			Category: categoryComputer,
			Weight:   1,
			Author: AuthorInfo{
				Name:    "兰德尔 E.布莱斯特",
				Country: countryAmerica,
			},
		},
		&Book{
			Id:       primitive.NewObjectID(),
			Name:     "深入理解Linux内核",
			Category: categoryComputer,
			Weight:   1,
			Author: AuthorInfo{
				Name:    "博韦,西斯特",
				Country: countryAmerica,
			},
		},
		&Book{
			Id:       primitive.NewObjectID(),
			Name:     "三体",
			Category: categorySciFi,
			Weight:   1,
			Author: AuthorInfo{
				Name:    "刘慈欣",
				Country: countryChina,
			},
		},
	}
)

func main() {
	uri := "mongodb://127.0.0.1:27017"
	db, e := mongo.Open(uri)
	if e != nil {
		panic(e)
	}

	e = db.Ping()
	if e != nil {
		panic(e)
	}
	clog.Println("MongoDb 链接成功")

	// 配置
	db.SetMaxOpenConn(1)
	db.SetConnMaxLifetime(400 * time.Millisecond)

	database := db.Database("okp")
	collection := database.Collection("BOOK")

	// 清空数据库和集合
	e = collection.Drop()

	idxRet, e := collection.CreatIndex("name", 1)
	if e != nil {
		panic(e)
	}
	log.Println("Collection.Indexes().CreateOne:", idxRet)

	// 插入一条数据
	insertOneResult, err := collection.InsertOne(context.TODO(), books[0])
	if err != nil {
		clog.PrintWa(err)
		log.Fatal()
	}

	log.Println("Collection.InsertOne:", insertOneResult.InsertedID)

	// 插入多条数据
	insertManyResult, err := collection.InsertMany(context.TODO(), books[1:])
	if err != nil {
		clog.PrintWa(err)
		log.Fatal(err)
	}
	log.Println("collection.InsertMany:", insertManyResult.InsertedIDs)

	// 获取数据总数
	count, err := collection.CountDocuments(context.TODO(), bson.D{})
	if err != nil {
		clog.PrintWa(err)
		log.Fatal(count)
	}
	log.Println("collection.CountDocuments:", count)

	// 查询单挑数据
	var one Book
	e = collection.FindOne(context.Background(), bson.M{"name": "三体"}).Decode(&one)
	if e != nil {
		clog.PrintWa(err)
		log.Fatal(err)
	}
	log.Println("collection.FindOne: ", one)

	// 查询多条数据 方式一
	cur, err := collection.Find(context.Background(), bson.D{})
	if err != nil {
		clog.PrintWa(err)
		log.Fatal(err)
	}
	if err := cur.Err(); err != nil {
		clog.PrintWa(err)
		log.Fatal(err)
	}
	var all []*Book
	err = cur.All(context.TODO(), &all)
	if err != nil {
		clog.PrintWa(err)
		log.Fatal(err)
	}

	cur.Close(context.TODO())

	log.Println("collection.Find curl.All", all)
	for _, one := range all {
		log.Println(one)
	}

	// 查询多条数据 方式二
	cur, err = collection.Find(context.Background(), bson.D{})
	if err != nil {
		log.Fatal(err)
	}
	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}
	for cur.Next(context.TODO()) {
		var b Book
		if err = cur.Decode(&b); err != nil {
			log.Fatal(err)
		}
		log.Println("collection.Find cur.Next:", b)
	}
	cur.Close(context.TODO())

	// 模糊查询
	cur, err = collection.Find(context.TODO(), bson.M{"name": primitive.Regex{Pattern: "深入"}})
	if err != nil {
		log.Fatal(err)
	}

	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

	for cur.Next(context.TODO()) {
		var b Book
		if err = cur.Decode(&b); err != nil {
			log.Fatal(err)
		}
		log.Println("collection.Find name=primitive.Regex{深入}: ", b)
	}
	cur.Close(context.TODO())

	// 二级结构体查询
	// 二级结构体查询
	cur, err = collection.Find(context.Background(), bson.M{"author.country": countryChina})
	// cur, err = collection.Find(context.Background(), bson.D{bson.E{"author.country", countryChina}})
	if err != nil {
		log.Fatal(err)
	}
	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}
	for cur.Next(context.Background()) {
		var b Book
		if err = cur.Decode(&b); err != nil {
			log.Fatal(err)
		}
		log.Println("collection.Find author.country=", countryChina, ":", b)
	}
	cur.Close(context.Background())

	// 修改一条数据
	b1 := books[0].(*Book)
	b1.Weight = 2
	update := bson.M{"$set": b1}
	updateResult, err := collection.UpdateOne(context.Background(), bson.M{"name": b1.Name}, update)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("collection.UpdateOne:", updateResult)

	// 修改一条数据,如果不存在则插入
	new := &Book{
		Id:       primitive.NewObjectID(),
		Name:     "球状闪电",
		Category: categorySciFi,
		Author: AuthorInfo{
			Name:    "刘慈欣",
			Country: countryChina,
		},
	}
	update = bson.M{"$set": new}
	updateOpts := options.Update().SetUpsert(true)
	updateResult, err = collection.UpdateOne(context.Background(), bson.M{"_id": new.Id}, update, updateOpts)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("collection.UpdateOne:", updateResult)

	// 删除一条数据
	deleteResult, err := collection.DeleteOne(context.Background(), bson.M{"_id": new.Id})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("collection.DeleteOne:", deleteResult)
}

Documentation

Overview

*

*

*

*

*

*

*

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Sha1Encode

func Sha1Encode(str string) string

获取sha1

Types

type Collection

type Collection struct {
	// contains filtered or unexported fields
}

func (*Collection) CountDocuments

func (c *Collection) CountDocuments() (int64, error)

获取总数

func (*Collection) CreatIndex

func (c *Collection) CreatIndex(key string, initial int32) (string, error)

设置索引

func (*Collection) DeleteOne

func (c *Collection) DeleteOne(ctx context.Context, filter interface{},
	opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

删除数据

func (*Collection) Drop

func (c *Collection) Drop() error

清空数据库

func (*Collection) Find

func (c *Collection) Find(ctx context.Context, filter interface{},
	opts ...*options.FindOptions) (*mongo.Cursor, error)

查询多条数据 方式一

func (*Collection) FindOne

func (c *Collection) FindOne(ctx context.Context, filter interface{},
	opts ...*options.FindOneOptions) *mongo.SingleResult

查询单条数据

func (*Collection) InsertMany

func (c *Collection) InsertMany(data []interface{}) (*mongo.InsertManyResult, error)

插件多条数据

func (*Collection) InsertOne

func (c *Collection) InsertOne(data interface{}) (*mongo.InsertOneResult, error)

插入一条数据

func (*Collection) UpdateOne

func (c *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{},
	opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

修改数据

type Database

type Database struct {
	// contains filtered or unexported fields
}

func (*Database) Collection

func (d *Database) Collection(name string, opts ...*options.CollectionOptions) *DbCollection

type Db

type Db struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

db

func Open

func Open(uri string) (*Db, error)

初始化db

func (*Db) Database

func (d *Db) Database(dbName string) *Database

func (*Db) GetCollection

func (d *Db) GetCollection(dbName, collectionName string) (collection *mongo.Collection, resultPul *ResultPul, err error)

暴露出去的 获取和放回

func (*Db) GetDatabase

func (d *Db) GetDatabase(dbName string) (database *mongo.Database, ResultDb *ResultDbPul, err error)

暴露

func (*Db) NewCollection

func (d *Db) NewCollection(dbName, collectionName string) *Collection

new

func (*Db) Ping

func (d *Db) Ping() error

链接检测数据库可用性

func (*Db) PulCollection

func (d *Db) PulCollection(resultPul *ResultPul) error

func (*Db) PulDatabase

func (d *Db) PulDatabase(pul *ResultDbPul) error

func (*Db) SetConnMaxLifetime

func (d *Db) SetConnMaxLifetime(time time.Duration)

设置超时时间

func (*Db) SetMaxOpenConn

func (d *Db) SetMaxOpenConn(maxOpen int)

设置最大打开数目

func (*Db) SetNotLimitedOpen

func (d *Db) SetNotLimitedOpen(open bool)

设置不限制打开数量

type DbCollection

type DbCollection struct {
	// contains filtered or unexported fields
}

func (*DbCollection) CountDocuments

func (d *DbCollection) CountDocuments(ctx context.Context, filter interface{},
	opts ...*options.CountOptions) (int64, error)

func (*DbCollection) CreatIndex

func (d *DbCollection) CreatIndex(key string, initial int32) (idxRet string, err error)

设置索引

func (*DbCollection) DeleteMany

func (d *DbCollection) DeleteMany(ctx context.Context, filter interface{},
	opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

func (*DbCollection) DeleteOne

func (d *DbCollection) DeleteOne(ctx context.Context, filter interface{},
	opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

func (*DbCollection) Drop

func (d *DbCollection) Drop() error

func (*DbCollection) Find

func (d *DbCollection) Find(ctx context.Context, filter interface{},
	opts ...*options.FindOptions) (*mongo.Cursor, error)

func (*DbCollection) FindOne

func (d *DbCollection) FindOne(ctx context.Context, filter interface{},
	opts ...*options.FindOneOptions) *mongo.SingleResult

func (*DbCollection) GetCollection

func (d *DbCollection) GetCollection() (*mongo.Collection, *ResultDbPul, error)

暴露出去

func (*DbCollection) Indexes

func (d *DbCollection) Indexes() mongo.IndexView

func (*DbCollection) InsertMany

func (d *DbCollection) InsertMany(ctx context.Context, documents []interface{},
	opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error)

func (*DbCollection) InsertOne

func (d *DbCollection) InsertOne(ctx context.Context, document interface{},
	opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)

func (*DbCollection) PulCollection

func (d *DbCollection) PulCollection(data *ResultDbPul) error

放回

func (*DbCollection) UpdateMany

func (d *DbCollection) UpdateMany(ctx context.Context, filter interface{}, update interface{},
	opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

func (*DbCollection) UpdateOne

func (d *DbCollection) UpdateOne(ctx context.Context, filter interface{}, update interface{},
	opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

type ObjPool

type ObjPool struct {
	// contains filtered or unexported fields
}

对象池

func NewObjPoll

func NewObjPoll(obj PoolGenerateItem, num int) *ObjPool

创建对象池

func (*ObjPool) GetObj

func (p *ObjPool) GetObj(timeout time.Duration) (interface{}, error)

获取对象

func (*ObjPool) Release

func (p *ObjPool) Release(obj interface{}) error

放回对象

type PoolGenerateItem

type PoolGenerateItem func() interface{}

type ResultDbPul

type ResultDbPul struct {
	// contains filtered or unexported fields
}

type ResultPul

type ResultPul struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis
* * @Author: DollarKiller * @Description: clog 日志打印 * @Github: https://github.com/dollarkillerx * @Date: Create in 09:16 2019-10-28
* * @Author: DollarKiller * @Description: clog 日志打印 * @Github: https://github.com/dollarkillerx * @Date: Create in 09:16 2019-10-28
examples
curd_demo1
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 16:21 2019-10-28
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 16:21 2019-10-28
db_pro
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 10:15 2019-10-29
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 10:15 2019-10-29
db_pro1
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 10:29 2019-10-29
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 10:29 2019-10-29
simple
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 20:42 2019-10-27
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 20:42 2019-10-27
simple_a
* * @Author: DollarKiller * @Description: 对外暴露 * @Github: https://github.com/dollarkillerx * @Date: Create in 14:03 2019-10-28
* * @Author: DollarKiller * @Description: 对外暴露 * @Github: https://github.com/dollarkillerx * @Date: Create in 14:03 2019-10-28
mongo-driver
bson
Package bson is a library for reading, writing, and manipulating BSON.
Package bson is a library for reading, writing, and manipulating BSON.
bson/bsoncodec
Package bsoncodec provides a system for encoding values to BSON representations and decoding values from BSON representations.
Package bsoncodec provides a system for encoding values to BSON representations and decoding values from BSON representations.
bson/bsonrw
Package bsonrw contains abstractions for reading and writing BSON and BSON like types from sources.
Package bsonrw contains abstractions for reading and writing BSON and BSON like types from sources.
bson/bsontype
Package bsontype is a utility package that contains types for each BSON type and the a stringifier for the Type to enable easier debugging when working with BSON.
Package bsontype is a utility package that contains types for each BSON type and the a stringifier for the Type to enable easier debugging when working with BSON.
bson/primitive
Package primitive contains types similar to Go primitives for BSON types can do not have direct Go primitive representations.
Package primitive contains types similar to Go primitives for BSON types can do not have direct Go primitive representations.
internal/testutil/israce
Package israce reports if the Go race detector is enabled.
Package israce reports if the Go race detector is enabled.
mongo
Package mongo provides a MongoDB Driver API for Go.
Package mongo provides a MongoDB Driver API for Go.
tag
x/bsonx/bsoncore
Package bsoncore contains functions that can be used to encode and decode BSON elements and values to or from a slice of bytes.
Package bsoncore contains functions that can be used to encode and decode BSON elements and values to or from a slice of bytes.
x/mongo/driver/auth
Package auth is not for public use.
Package auth is not for public use.
x/mongo/driver/topology
Package topology contains types that handles the discovery, monitoring, and selection of servers.
Package topology contains types that handles the discovery, monitoring, and selection of servers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL