4 Star 5 Fork 4

Plato/Service-Box-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.vscode
common
example
internal
util
config
errors
http_proxy
jwt_auth
mongodb
mongodb.go
mongodb_test.go
options.go
redis
scli
service_infra
slog
tools
uuid
.gitignore
LICENSE
box.go
box_linux.go
box_test.go
box_windows.go
channel.go
constants.go
default.yaml
go.mod
network.go
options.go
options_test.go
proxy_handle.go
proxy_handle_test.go
service_layer.go
service_layer_test.go
service_watcher.go
test_app.yaml
test_direct_connect.yaml
test_http_proxy.yaml
克隆/下载
mongodb.go 1.50 KB
一键复制 编辑 原始数据 按行查看 历史
CloudGuan 提交于 3年前 . update: mongo db 接入
package mongodb
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type (
MongoDB struct {
//options mongo需要的配置
options *Options
//client mongo 客户端
client *mongo.Client
//collections Collection缓存
collections map[string]*mongo.Collection
}
)
func NewMongoDB(opts ...Option) *MongoDB {
option := &Options{}
for _, opt := range opts {
opt(option)
}
return &MongoDB{
option,
nil,
make(map[string]*mongo.Collection),
}
}
//Init 初始化, 处理用户配置,生成mongo uri
func (db *MongoDB) Init(opts ...Option) error {
for _, opt := range opts {
opt(db.options)
}
uri, err := db.options.genMongoUri()
if err != nil {
return err
}
// 连接到mongo
db.client, err = mongo.Connect(context.Background(), options.Client().ApplyURI(uri))
if err != nil {
return err
}
return nil
}
func (db *MongoDB) Start() error {
// ping 测试连通性, 确定已经连接好
err := db.client.Ping(context.Background(), readpref.Primary())
if err != nil {
return err
}
return nil
}
func (db *MongoDB) UnInit() error {
db.collections = nil
return db.client.Disconnect(context.Background())
}
func (db *MongoDB) IsInvalid() bool {
return db.client != nil
}
func (db *MongoDB) GetCollection(name string) *mongo.Collection {
if co, ok := db.collections[name]; ok {
return co
}
co := db.client.Database(db.options.DB).Collection(name)
db.collections[name] = co
return co
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dennis-kk/service-box-go.git
git@gitee.com:dennis-kk/service-box-go.git
dennis-kk
service-box-go
Service-Box-go
v0.4.17

搜索帮助