-
Notifications
You must be signed in to change notification settings - Fork 1
/
publisher.go
91 lines (80 loc) · 1.84 KB
/
publisher.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
package rabbitmqclient
import (
"fmt"
"sync/atomic"
"github.com/fairyhunter13/amqpwrapper"
"github.com/streadway/amqp"
)
type publisherManager struct {
conn amqpwrapper.IConnectionManager
channelCounter uint64
idleChannels chan uint64
}
func newPublisherManager(conn amqpwrapper.IConnectionManager) (res *publisherManager) {
res = new(publisherManager)
res.idleChannels = make(chan uint64)
res.conn = conn
return
}
func (pm *publisherManager) publish(arg Publish) (err error) {
if pm.conn.IsClosed() {
err = ErrConnectionAlreadyClosed
return
}
var (
idChannel uint64
isNew bool
more bool
)
select {
case idChannel, more = <-pm.idleChannels:
if !more {
return
}
isNew = false
default:
isNew = true
}
defer pm.releaseChannel(&idChannel)
err = pm.publishWithChannel(&idChannel, arg, isNew)
return
}
func (pm *publisherManager) publishWithChannel(idChan *uint64, arg Publish, isNew bool) (err error) {
var (
ch *amqp.Channel
)
ch, err = pm.getChannel(idChan, isNew)
if err != nil {
return
}
err = ch.Publish(arg.Exchange, arg.Key, arg.Mandatory, arg.Immediate, arg.Msg)
return
}
func (pm *publisherManager) getChannel(idChan *uint64, isNew bool) (ch *amqp.Channel, err error) {
var (
keyChannel string
)
if isNew {
*idChan = atomic.LoadUint64(&pm.channelCounter)
atomic.AddUint64(&pm.channelCounter, 1)
}
keyChannel = fmt.Sprintf(DefaultKeyProducer, *idChan)
if isNew {
ch, err = pm.conn.InitChannelAndGet(EmptyFn, amqpwrapper.InitArgs{
Key: keyChannel,
TypeChan: DefaultTypeProducer,
})
} else {
ch, err = pm.conn.GetChannel(keyChannel, DefaultTypeProducer)
}
return
}
func (pm *publisherManager) releaseChannel(idChannel *uint64) {
idLocal := *idChannel
go func() {
pm.idleChannels <- idLocal
}()
}
func (pm *publisherManager) close() {
close(pm.idleChannels)
}