feat 初始化

This commit is contained in:
2026-10-29 10:12:22 +08:00
parent 332d812347
commit 09c1df8a22
81 changed files with 2211 additions and 7821 deletions

View File

@@ -4,8 +4,17 @@ import (
"context"
"git.hlsq.asia/alex/service-common/config"
"git.hlsq.asia/alex/service-common/log"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"time"
)
// Colors
const (
Reset = "\033[0m"
BrightGreen = "\033[92m"
)
type DBName string
@@ -25,12 +34,27 @@ func Init(cfg map[string]*config.MongoConfig) error {
func initOneClient(cfg *config.MongoConfig) (*mongo.Client, error) {
opts := options.Client().
ApplyURI(cfg.URI)
ApplyURI(cfg.URI).
SetMonitor(&event.CommandMonitor{
Started: func(ctx context.Context, startedEvent *event.CommandStartedEvent) {
log.Infof(BrightGreen+"[MongoDB] Started, Command: %v"+Reset, startedEvent.Command.String())
},
Failed: func(ctx context.Context, failedEvent *event.CommandFailedEvent) {
log.Errorf(BrightGreen+"[MongoDB] [%v] Failed, Failure: %v"+Reset, failedEvent.Duration, failedEvent.Failure)
},
})
client, err := mongo.Connect(context.Background(), opts)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, opts)
if err != nil {
return nil, err
}
if err = client.Ping(ctx, readpref.Primary()); err != nil {
_ = client.Disconnect(context.Background())
return nil, err
}
return client, nil
}