feat: use mongodb official driver instead of mgo (#1782)
* wip: backup * wip: backup * wip: backup * backup * backup * backup * add more tests * fix wrong dependency * fix lint errors * remove test due to data race * add tests * fix test error * add mon.Model * add mon.Model unmarshal * add monc * add more tests for monc * add more tests for monc * add docs for mon and monc packages * fix doc errors * chhore: add comment * chore: fix test bug * chore: refine tests * chore: remove primitive.NewObjectID in test code * chore: rename test files for typo
This commit is contained in:
51
core/stores/mon/clientmanager.go
Normal file
51
core/stores/mon/clientmanager.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package mon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/syncx"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
mopt "go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
const defaultTimeout = time.Second
|
||||
|
||||
var clientManager = syncx.NewResourceManager()
|
||||
|
||||
// ClosableClient wraps *mongo.Client and provides a Close method.
|
||||
type ClosableClient struct {
|
||||
*mongo.Client
|
||||
}
|
||||
|
||||
// Close disconnects the underlying *mongo.Client.
|
||||
func (cs *ClosableClient) Close() error {
|
||||
return cs.Client.Disconnect(context.Background())
|
||||
}
|
||||
|
||||
// Inject injects a *mongo.Client into the client manager.
|
||||
// Typically, this is used to inject a *mongo.Client for test purpose.
|
||||
func Inject(key string, client *mongo.Client) {
|
||||
clientManager.Inject(key, &ClosableClient{client})
|
||||
}
|
||||
|
||||
func getClient(url string) (*mongo.Client, error) {
|
||||
val, err := clientManager.GetResource(url, func() (io.Closer, error) {
|
||||
cli, err := mongo.Connect(context.Background(), mopt.Client().ApplyURI(url))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
concurrentSess := &ClosableClient{
|
||||
Client: cli,
|
||||
}
|
||||
|
||||
return concurrentSess, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return val.(*ClosableClient).Client, nil
|
||||
}
|
||||
Reference in New Issue
Block a user