Go语言 如何超时等待一个Redis池

eulz3vhy  于 2023-10-14  发布在  Go
关注(0)|答案(1)|浏览(135)

我正在使用https://github.com/gomodule/redigo作为我的池化redis连接,
redis.Pool结构如下所示

  1. type Pool struct {
  2. // Dial is an application supplied function for creating and configuring a
  3. // connection.
  4. //
  5. // The connection returned from Dial must not be in a special state
  6. // (subscribed to pubsub channel, transaction started, ...).
  7. Dial func() (Conn, error)
  8. // DialContext is an application supplied function for creating and configuring a
  9. // connection with the given context.
  10. //
  11. // The connection returned from Dial must not be in a special state
  12. // (subscribed to pubsub channel, transaction started, ...).
  13. DialContext func(ctx context.Context) (Conn, error)
  14. // TestOnBorrow is an optional application supplied function for checking
  15. // the health of an idle connection before the connection is used again by
  16. // the application. Argument t is the time that the connection was returned
  17. // to the pool. If the function returns an error, then the connection is
  18. // closed.
  19. TestOnBorrow func(c Conn, t time.Time) error
  20. // Maximum number of idle connections in the pool.
  21. MaxIdle int
  22. // Maximum number of connections allocated by the pool at a given time.
  23. // When zero, there is no limit on the number of connections in the pool.
  24. MaxActive int
  25. // Close connections after remaining idle for this duration. If the value
  26. // is zero, then idle connections are not closed. Applications should set
  27. // the timeout to a value less than the server's timeout.
  28. IdleTimeout time.Duration
  29. // If Wait is true and the pool is at the MaxActive limit, then Get() waits
  30. // for a connection to be returned to the pool before returning.
  31. Wait bool
  32. // Close connections older than this duration. If the value is zero, then
  33. // the pool does not close connections based on age.
  34. MaxConnLifetime time.Duration
  35. mu sync.Mutex // mu protects the following fields
  36. closed bool // set to true when the pool is closed.
  37. active int // the number of open connections in the pool
  38. initOnce sync.Once // the init ch once func
  39. ch chan struct{} // limits open connections when p.Wait is true
  40. idle idleList // idle connections
  41. waitCount int64 // total number of connections waited for.
  42. waitDuration time.Duration // total time waited for new connections.
  43. }

pool.Get函数从池中获取连接,如果Wait标志打开,则等待连接可用
有没有办法设置这个等待时间的超时?

pkbketx9

pkbketx91#

对可取消的上下文使用GetContext。

  1. ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
  2. defer cancel()
  3. conn, err := pool.GetContext(ctx)

相关问题