-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpool.go
155 lines (134 loc) · 2.47 KB
/
pool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package rabbit_ch_pool
import (
"github.com/streadway/amqp"
"sync"
"time"
)
// Pooler pool interface
type Pooler interface {
Get() (*amqp.Channel, error)
Put(ch *amqp.Channel) error
}
// ChannelPool pool struct
type ChannelPool struct {
conn *amqp.Connection
chMu sync.Mutex
chPool chan *amqp.Channel
exchangeDeclare bool
exchangeName string
exchangeType string
poolSize int
poolTimeout time.Duration
}
// NewChannelPool create new pool with amqp channels
func NewChannelPool(opt *Options, conn *amqp.Connection) *ChannelPool {
p := &ChannelPool{
conn: conn,
poolSize: opt.PoolSize,
poolTimeout: opt.PoolTimeout,
}
if opt.PoolTimeout == 0 {
p.poolTimeout = 10
}
if opt.PoolSize == 0 {
p.chPool = make(chan *amqp.Channel, 5)
} else {
p.chPool = make(chan *amqp.Channel, opt.PoolSize)
}
p.clearPool()
for i := 0; i < p.poolSize; i++ {
err := p.spawnChannel()
if err != nil {
return nil
}
}
return p
}
func (p *ChannelPool) spawnChannel() error {
ch, err := p.conn.Channel()
if err != nil {
return err
}
if p.exchangeDeclare {
err = ch.ExchangeDeclare(
p.exchangeName,
p.exchangeType,
false,
false,
false,
false,
nil,
)
if err != nil {
return err
}
}
p.chMu.Lock()
if len(p.chPool) < p.poolSize {
p.chPool <- ch
} else {
ch.Close()
}
p.chMu.Unlock()
return nil
}
func (p *ChannelPool) _getChannel() (*amqp.Channel, error) {
timeout := time.After(p.poolTimeout * time.Second)
loop:
for {
select {
case rCh := <-p.chPool:
err := rCh.Confirm(false)
if err == nil {
return rCh, nil
}
if err == amqp.ErrClosed {
err = p.spawnChannel()
if err != nil {
break loop
}
break
} else {
return nil, amqp.ErrClosed
}
case <-timeout:
break loop
}
}
return nil, amqp.ErrClosed
}
func (p *ChannelPool) _releaseChannel(ch *amqp.Channel) error {
err := ch.Confirm(false)
if err != nil {
err = p.spawnChannel()
return err
}
p.chMu.Lock()
if len(p.chPool) < p.poolSize {
p.chPool <- ch
} else {
ch.Close()
}
p.chMu.Unlock()
return nil
}
func (p *ChannelPool) clearPool() {
if len(p.chPool) != 0 {
L:
for {
select {
case <-p.chPool:
default:
break L
}
}
}
}
// Get get channel from pool
func (p *ChannelPool) Get() (*amqp.Channel, error) {
return p._getChannel()
}
// Put put channel to pool
func (p *ChannelPool) Put(ch *amqp.Channel) error {
return p._releaseChannel(ch)
}