conn.go 926 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package nsqclient
  2. import (
  3. "sync"
  4. nsq "github.com/nsqio/go-nsq"
  5. )
  6. // PoolConn is a wrapper around net.Conn to modify the the behavior of
  7. // net.Conn's Close() method.
  8. type PoolConn struct {
  9. *nsq.Producer
  10. mu sync.RWMutex
  11. c *channelPool
  12. unusable bool
  13. }
  14. // Close puts the given connects back to the pool instead of closing it.
  15. func (p *PoolConn) Close() error {
  16. p.mu.RLock()
  17. defer p.mu.RUnlock()
  18. if p.unusable {
  19. if p.Producer != nil {
  20. p.Producer.Stop()
  21. return nil
  22. }
  23. return nil
  24. }
  25. return p.c.put(p.Producer)
  26. }
  27. // MarkUnusable marks the connection not usable any more, to let the pool close it instead of returning it to pool.
  28. func (p *PoolConn) MarkUnusable() {
  29. p.mu.Lock()
  30. p.unusable = true
  31. p.mu.Unlock()
  32. }
  33. // newConn wraps a standard net.Conn to a poolConn net.Conn.
  34. func (c *channelPool) wrapConn(conn *nsq.Producer) *PoolConn {
  35. p := &PoolConn{c: c}
  36. p.Producer = conn
  37. return p
  38. }