MCPcopy
hub / github.com/redis/go-redis / Close

Method Close

internal/pool/pool.go:1655–1712  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

1653}
1654
1655func (p *ConnPool) Close() error {
1656 if !atomic.CompareAndSwapUint32(&p._closed, 0, 1) {
1657 return ErrClosed
1658 }
1659
1660 var firstErr error
1661 nowNs := time.Now().UnixNano()
1662 p.connsMu.Lock()
1663
1664 // Emit -1 for each connection. Since all idle↔used transitions happen
1665 // under connsMu, the idleConns slice is the source of truth for state.
1666 cb := getMetricConnectionCountCallback()
1667 idleSet := make(map[uint64]struct{}, len(p.idleConns))
1668 for _, cn := range p.idleConns {
1669 idleSet[cn.GetID()] = struct{}{}
1670 }
1671 ctx := context.Background()
1672 for _, cn := range p.conns {
1673 // Check health before closing, since closeConn invalidates the
1674 // underlying fd and would make connCheck (inside isHealthyConn)
1675 // always fail with EBADF.
1676 // Only check health for idle connections to avoid data races when
1677 // peeking at the socket/reader while another goroutine is reading from it.
1678 // Non-idle connections are either in use or in transitional states and
1679 // shouldn't be health-checked during shutdown.
1680 _, isIdle := idleSet[cn.GetID()]
1681 var healthy bool
1682 if isIdle {
1683 healthy = p.isHealthyConn(cn, nowNs)
1684 } else {
1685 healthy = true
1686 }
1687 if cb != nil {
1688 if isIdle {
1689 cb(ctx, -1, cn, "idle", false)
1690 } else {
1691 cb(ctx, -1, cn, "used", false)
1692 }
1693 }
1694 if closedCb := getMetricConnectionClosedCallback(); closedCb != nil {
1695 closedCb(ctx, cn, "pool_shutdown", nil)
1696 }
1697 if err := p.closeConn(cn); err != nil && firstErr == nil {
1698 // Suppress close errors for stale connections, consistent
1699 // with how Get() handles them (see CloseReasonStale path).
1700 if healthy {
1701 firstErr = err
1702 }
1703 }
1704 }
1705 p.conns = nil
1706 p.poolSize.Store(0)
1707 p.idleConns = nil
1708 p.idleConnsLen.Store(0)
1709 p.connsMu.Unlock()
1710
1711 return firstErr
1712}

Calls 5

isHealthyConnMethod · 0.95
closeConnMethod · 0.95
GetIDMethod · 0.80