common.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package client
  2. import (
  3. "context"
  4. "github.com/milvus-io/milvus/client/v2/entity"
  5. "github.com/milvus-io/milvus/pkg/util/conc"
  6. "github.com/milvus-io/milvus/pkg/util/typeutil"
  7. )
  8. // CollectionCache stores the cached collection schema information.
  9. type CollectionCache struct {
  10. sf conc.Singleflight[*entity.Collection]
  11. collections *typeutil.ConcurrentMap[string, *entity.Collection]
  12. fetcher func(context.Context, string) (*entity.Collection, error)
  13. }
  14. func (c *CollectionCache) GetCollection(ctx context.Context, collName string) (*entity.Collection, error) {
  15. coll, ok := c.collections.Get(collName)
  16. if ok {
  17. return coll, nil
  18. }
  19. coll, err, _ := c.sf.Do(collName, func() (*entity.Collection, error) {
  20. coll, err := c.fetcher(ctx, collName)
  21. if err != nil {
  22. return nil, err
  23. }
  24. c.collections.Insert(collName, coll)
  25. return coll, nil
  26. })
  27. return coll, err
  28. }
  29. // Reset clears all cached info, used when client switching env.
  30. func (c *CollectionCache) Reset() {
  31. c.collections = typeutil.NewConcurrentMap[string, *entity.Collection]()
  32. }
  33. func NewCollectionCache(fetcher func(context.Context, string) (*entity.Collection, error)) *CollectionCache {
  34. return &CollectionCache{
  35. collections: typeutil.NewConcurrentMap[string, *entity.Collection](),
  36. fetcher: fetcher,
  37. }
  38. }
  39. func (c *Client) getCollection(ctx context.Context, collName string) (*entity.Collection, error) {
  40. return c.collCache.GetCollection(ctx, collName)
  41. }