-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.go
64 lines (57 loc) · 1.59 KB
/
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 queue
import (
"fmt"
"github.com/streadway/amqp"
"log"
)
// Publish a Protocol Buffer to an AMQP Exchange
//
// @param {String} key
// @param {[]byte} body
// @param {*amqp.Connection} connection
// @return {error}
// @api public
func Publish(key string, body []byte, connection *amqp.Connection) error {
channel, err := connection.Channel()
if err != nil {
return fmt.Errorf("Channel: %s", err)
}
defer channel.Close()
// Reliable publisher confirms require confirm.select support from the
// connection.
if reliable {
if err := channel.Confirm(false); err != nil {
return fmt.Errorf("Channel could not be put into confirm mode: %s", err)
}
ack, nack := channel.NotifyConfirm(make(chan uint64), make(chan uint64))
defer confirmOne(ack, nack)
}
if err = channel.Publish(
exchangeName, // publish to an exchange
key, // routing to 0 or more queues
true, // mandatory
false, // immediate
amqp.Publishing{
Headers: amqp.Table{},
ContentType: "",
ContentEncoding: "",
Body: body,
DeliveryMode: amqp.Persistent,
Priority: 0, // 0-9
},
); err != nil {
return fmt.Errorf("Exchange Publish: %s", err)
}
return nil
}
// One would typically keep a channel of publishings, a sequence number, and a
// set of unacknowledged sequence numbers and loop until the publishing channel
// is closed.
func confirmOne(ack, nack chan uint64) {
select {
case tag := <-ack:
log.Printf("confirmed delivery with delivery tag: %d", tag)
case tag := <-nack:
log.Printf("failed delivery of delivery tag: %d", tag)
}
}