-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsync_producer.go
64 lines (52 loc) · 1.48 KB
/
sync_producer.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
package mq
import (
"sync"
"github.com/NeowayLabs/wabbit"
)
// SyncProducer describes available methods for synchronous producer.
type SyncProducer interface {
// Produce sends message to broker. Waits for result (ok, error).
Produce(data []byte) error
}
type syncProducer struct {
sync.Mutex // Protect channel during posting and reconnect.
errorChannel chan<- error
channel wabbit.Channel
exchange string
options wabbit.Option
routingKey string
}
func newSyncProducer(channel wabbit.Channel, errorChannel chan<- error, config ProducerConfig) *syncProducer {
return &syncProducer{
channel: channel,
errorChannel: errorChannel,
exchange: config.Exchange,
options: wabbit.Option(config.Options),
routingKey: config.RoutingKey,
}
}
func (producer *syncProducer) init() {
// Do nothing. Already inited.
}
// Method safely sets new RMQ channel.
func (producer *syncProducer) setChannel(channel wabbit.Channel) {
producer.Lock()
producer.channel = channel
producer.Unlock()
}
func (producer *syncProducer) Produce(message []byte) error {
producer.Lock()
defer producer.Unlock()
return producer.channel.Publish(producer.exchange, producer.routingKey, message, producer.options)
}
func (producer *syncProducer) Stop() {
producer.closeChannel()
}
// Close producer's channel.
func (producer *syncProducer) closeChannel() {
producer.Lock()
if err := producer.channel.Close(); err != nil {
producer.errorChannel <- err
}
producer.Unlock()
}