...
1 package pool
2
3 import "sync"
4
5 type StickyConnPool struct {
6 pool *ConnPool
7 reusable bool
8
9 cn *Conn
10 closed bool
11 mu sync.Mutex
12 }
13
14 var _ Pooler = (*StickyConnPool)(nil)
15
16 func NewStickyConnPool(pool *ConnPool, reusable bool) *StickyConnPool {
17 return &StickyConnPool{
18 pool: pool,
19 reusable: reusable,
20 }
21 }
22
23 func (p *StickyConnPool) NewConn() (*Conn, error) {
24 panic("not implemented")
25 }
26
27 func (p *StickyConnPool) CloseConn(*Conn) error {
28 panic("not implemented")
29 }
30
31 func (p *StickyConnPool) Get() (*Conn, error) {
32 p.mu.Lock()
33 defer p.mu.Unlock()
34
35 if p.closed {
36 return nil, ErrClosed
37 }
38 if p.cn != nil {
39 return p.cn, nil
40 }
41
42 cn, err := p.pool.Get()
43 if err != nil {
44 return nil, err
45 }
46
47 p.cn = cn
48 return cn, nil
49 }
50
51 func (p *StickyConnPool) putUpstream() {
52 p.pool.Put(p.cn)
53 p.cn = nil
54 }
55
56 func (p *StickyConnPool) Put(cn *Conn) {}
57
58 func (p *StickyConnPool) removeUpstream(reason error) {
59 p.pool.Remove(p.cn, reason)
60 p.cn = nil
61 }
62
63 func (p *StickyConnPool) Remove(cn *Conn, reason error) {
64 p.removeUpstream(reason)
65 }
66
67 func (p *StickyConnPool) Len() int {
68 p.mu.Lock()
69 defer p.mu.Unlock()
70
71 if p.cn == nil {
72 return 0
73 }
74 return 1
75 }
76
77 func (p *StickyConnPool) IdleLen() int {
78 p.mu.Lock()
79 defer p.mu.Unlock()
80
81 if p.cn == nil {
82 return 1
83 }
84 return 0
85 }
86
87 func (p *StickyConnPool) Stats() *Stats {
88 return nil
89 }
90
91 func (p *StickyConnPool) Close() error {
92 p.mu.Lock()
93 defer p.mu.Unlock()
94
95 if p.closed {
96 return ErrClosed
97 }
98 p.closed = true
99
100 if p.cn != nil {
101 if p.reusable {
102 p.putUpstream()
103 } else {
104 p.removeUpstream(ErrClosed)
105 }
106 }
107
108 return nil
109 }
110
View as plain text