本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
1.5KB

  1. package pool
  2. import "sync"
  3. type StickyConnPool struct {
  4. pool *ConnPool
  5. reusable bool
  6. cn *Conn
  7. closed bool
  8. mu sync.Mutex
  9. }
  10. var _ Pooler = (*StickyConnPool)(nil)
  11. func NewStickyConnPool(pool *ConnPool, reusable bool) *StickyConnPool {
  12. return &StickyConnPool{
  13. pool: pool,
  14. reusable: reusable,
  15. }
  16. }
  17. func (p *StickyConnPool) NewConn() (*Conn, error) {
  18. panic("not implemented")
  19. }
  20. func (p *StickyConnPool) CloseConn(*Conn) error {
  21. panic("not implemented")
  22. }
  23. func (p *StickyConnPool) Get() (*Conn, error) {
  24. p.mu.Lock()
  25. defer p.mu.Unlock()
  26. if p.closed {
  27. return nil, ErrClosed
  28. }
  29. if p.cn != nil {
  30. return p.cn, nil
  31. }
  32. cn, err := p.pool.Get()
  33. if err != nil {
  34. return nil, err
  35. }
  36. p.cn = cn
  37. return cn, nil
  38. }
  39. func (p *StickyConnPool) putUpstream() {
  40. p.pool.Put(p.cn)
  41. p.cn = nil
  42. }
  43. func (p *StickyConnPool) Put(cn *Conn) {}
  44. func (p *StickyConnPool) removeUpstream() {
  45. p.pool.Remove(p.cn)
  46. p.cn = nil
  47. }
  48. func (p *StickyConnPool) Remove(cn *Conn) {
  49. p.removeUpstream()
  50. }
  51. func (p *StickyConnPool) Len() int {
  52. p.mu.Lock()
  53. defer p.mu.Unlock()
  54. if p.cn == nil {
  55. return 0
  56. }
  57. return 1
  58. }
  59. func (p *StickyConnPool) IdleLen() int {
  60. p.mu.Lock()
  61. defer p.mu.Unlock()
  62. if p.cn == nil {
  63. return 1
  64. }
  65. return 0
  66. }
  67. func (p *StickyConnPool) Stats() *Stats {
  68. return nil
  69. }
  70. func (p *StickyConnPool) Close() error {
  71. p.mu.Lock()
  72. defer p.mu.Unlock()
  73. if p.closed {
  74. return ErrClosed
  75. }
  76. p.closed = true
  77. if p.cn != nil {
  78. if p.reusable {
  79. p.putUpstream()
  80. } else {
  81. p.removeUpstream()
  82. }
  83. }
  84. return nil
  85. }
上海开阖软件有限公司 沪ICP备12045867号-1