clientmanager.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package mon
  2. import (
  3. "context"
  4. "io"
  5. "time"
  6. "github.com/zeromicro/go-zero/core/syncx"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. mopt "go.mongodb.org/mongo-driver/mongo/options"
  9. )
  10. const defaultTimeout = time.Second
  11. var clientManager = syncx.NewResourceManager()
  12. // ClosableClient wraps *mongo.Client and provides a Close method.
  13. type ClosableClient struct {
  14. *mongo.Client
  15. }
  16. // Close disconnects the underlying *mongo.Client.
  17. func (cs *ClosableClient) Close() error {
  18. return cs.Client.Disconnect(context.Background())
  19. }
  20. // Inject injects a *mongo.Client into the client manager.
  21. // Typically, this is used to inject a *mongo.Client for test purpose.
  22. func Inject(key string, client *mongo.Client) {
  23. clientManager.Inject(key, &ClosableClient{client})
  24. }
  25. func getClient(url string) (*mongo.Client, error) {
  26. val, err := clientManager.GetResource(url, func() (io.Closer, error) {
  27. cli, err := mongo.Connect(context.Background(), mopt.Client().ApplyURI(url))
  28. if err != nil {
  29. return nil, err
  30. }
  31. concurrentSess := &ClosableClient{
  32. Client: cli,
  33. }
  34. return concurrentSess, nil
  35. })
  36. if err != nil {
  37. return nil, err
  38. }
  39. return val.(*ClosableClient).Client, nil
  40. }