-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublisher.go
62 lines (56 loc) · 1.2 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
package carrot
import (
"fmt"
"time"
"github.com/streadway/amqp"
)
type Publisher struct {
client *BrokerClient
}
//Message encapsulate some data configuration
type Message struct {
Data []byte
ContentType string
Encoding string
Headers map[string]interface{}
}
//Publish a message to exchange in routingkey
func (pub *Publisher) Publish(exchange, routingKey string, message Message) error {
err := fmt.Errorf("begin")
var ch *amqp.Channel
for err != nil {
if pub.client.client != nil {
ch, err = pub.client.client.Channel()
if err == nil {
err = ch.Publish(
exchange,
routingKey,
false,
false,
amqp.Publishing{
Headers: message.Headers,
ContentType: message.ContentType,
ContentEncoding: message.Encoding,
Body: message.Data,
DeliveryMode: amqp.Persistent,
Priority: 0,
},
)
if err == nil {
ch.Close()
}
}
}
if err != nil {
err = pub.client.Reconnect()
time.Sleep(1 * time.Second)
}
}
return err
}
//NewPublisher creates a new broker publisher
func NewPublisher(client *BrokerClient) *Publisher {
pub := new(Publisher)
pub.client = client
return pub
}