pool.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package ldap
  2. import (
  3. "sync"
  4. )
  5. type ConnectionPool struct {
  6. pool chan interface{} // 连接缓冲池
  7. factory func() (interface{}, error) // 创建新连接的工厂方法
  8. size int // 连接池大小
  9. mu sync.Mutex // 并发控制
  10. closed bool // 标记连接池是否已关闭
  11. }
  12. func NewConnectionPool(size int, factory func() (interface{}, error)) *ConnectionPool {
  13. return &ConnectionPool{
  14. pool: make(chan interface{}, size),
  15. factory: factory,
  16. size: size,
  17. }
  18. }
  19. func (p *ConnectionPool) Acquire() (interface{}, error) {
  20. select {
  21. case conn := <-p.pool:
  22. return conn, nil
  23. default:
  24. return p.factory()
  25. }
  26. }
  27. func (p *ConnectionPool) Release(conn interface{}) {
  28. if conn == nil {
  29. return
  30. }
  31. select {
  32. case p.pool <- conn:
  33. default:
  34. if closer, ok := conn.(interface{ Close() }); ok {
  35. closer.Close()
  36. }
  37. }
  38. }
  39. func (p *ConnectionPool) Close() {
  40. p.mu.Lock()
  41. defer p.mu.Unlock()
  42. if !p.closed {
  43. p.closed = true
  44. close(p.pool)
  45. for conn := range p.pool {
  46. // 关闭连接
  47. if closer, ok := conn.(interface{ Close() }); ok {
  48. closer.Close()
  49. }
  50. }
  51. }
  52. }