pool.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package pool
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "time"
  7. xtime "go-common/library/time"
  8. )
  9. var (
  10. // ErrPoolExhausted connections are exhausted.
  11. ErrPoolExhausted = errors.New("container/pool exhausted")
  12. // ErrPoolClosed connection pool is closed.
  13. ErrPoolClosed = errors.New("container/pool closed")
  14. // nowFunc returns the current time; it's overridden in tests.
  15. nowFunc = time.Now
  16. )
  17. // Config is the pool configuration struct.
  18. type Config struct {
  19. // Active number of items allocated by the pool at a given time.
  20. // When zero, there is no limit on the number of items in the pool.
  21. Active int
  22. // Idle number of idle items in the pool.
  23. Idle int
  24. // Close items after remaining item for this duration. If the value
  25. // is zero, then item items are not closed. Applications should set
  26. // the timeout to a value less than the server's timeout.
  27. IdleTimeout xtime.Duration
  28. // If WaitTimeout is set and the pool is at the Active limit, then Get() waits WatiTimeout
  29. // until a item to be returned to the pool before returning.
  30. WaitTimeout xtime.Duration
  31. // If WaitTimeout is not set, then Wait effects.
  32. // if Wait is set true, then wait until ctx timeout, or default flase and return directly.
  33. Wait bool
  34. }
  35. type item struct {
  36. createdAt time.Time
  37. c io.Closer
  38. }
  39. func (i *item) expired(timeout time.Duration) bool {
  40. if timeout <= 0 {
  41. return false
  42. }
  43. return i.createdAt.Add(timeout).Before(nowFunc())
  44. }
  45. func (i *item) close() error {
  46. return i.c.Close()
  47. }
  48. // Pool interface.
  49. type Pool interface {
  50. Get(ctx context.Context) (io.Closer, error)
  51. Put(ctx context.Context, c io.Closer, forceClose bool) error
  52. Close() error
  53. }