-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrabbit.go
More file actions
63 lines (51 loc) · 1.34 KB
/
rabbit.go
File metadata and controls
63 lines (51 loc) · 1.34 KB
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
package main
import (
"fmt"
"os"
"github.com/streadway/amqp"
)
type Connection struct {
conn *amqp.Connection
channel *amqp.Channel
queue amqp.Queue
}
func Connect() *Connection {
user := os.Getenv("RABBIT_USER")
passwd := os.Getenv("RABBIT_PASSWD")
url := os.Getenv("RABBIT_URL")
port := os.Getenv("RABBIT_PORT")
connString := fmt.Sprintf("amqp://%s:%s@%s:%s/", user, passwd, url, port)
conn, err := amqp.Dial(connString)
failOnError(err, "Failed to connect to RabbitMQ")
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
q, err := ch.QueueDeclare(
"task_queue", // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
return &Connection{conn, ch, q}
}
func (conn *Connection) Publish(msg []byte) error {
return conn.channel.Publish(
"", // exchange
conn.queue.Name, // routing key
false, // mandatory
false,
amqp.Publishing{
DeliveryMode: amqp.Persistent,
ContentType: "text/xml",
Body: []byte(msg),
})
}
func (conn *Connection) Close() error {
err := conn.conn.Close()
failOnError(err, "Failed to close connection.")
err = conn.channel.Close()
failOnError(err, "Failed to close channel.")
return err
}