12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package ldap
- import (
- "sync"
- )
- type ConnectionPool struct {
- pool chan interface{} // 连接缓冲池
- factory func() (interface{}, error) // 创建新连接的工厂方法
- size int // 连接池大小
- mu sync.Mutex // 并发控制
- closed bool // 标记连接池是否已关闭
- }
- func NewConnectionPool(size int, factory func() (interface{}, error)) *ConnectionPool {
- return &ConnectionPool{
- pool: make(chan interface{}, size),
- factory: factory,
- size: size,
- }
- }
- func (p *ConnectionPool) Acquire() (interface{}, error) {
- select {
- case conn := <-p.pool:
- return conn, nil
- default:
- return p.factory()
- }
- }
- func (p *ConnectionPool) Release(conn interface{}) {
- if conn == nil {
- return
- }
- select {
- case p.pool <- conn:
- default:
- if closer, ok := conn.(interface{ Close() }); ok {
- closer.Close()
- }
- }
- }
- func (p *ConnectionPool) Close() {
- p.mu.Lock()
- defer p.mu.Unlock()
- if !p.closed {
- p.closed = true
- close(p.pool)
- for conn := range p.pool {
- // 关闭连接
- if closer, ok := conn.(interface{ Close() }); ok {
- closer.Close()
- }
- }
- }
- }
|