-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathamqp.go
116 lines (91 loc) · 2.15 KB
/
amqp.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package queue
import "github.com/streadway/amqp"
// AMQPBackend provides AMQP-based backend to manage queues.
// https://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol
// Suitable for multi-host, multi-process and multithreaded environment
type AMQPBackend struct {
conn *amqp.Connection
codec Codec
}
// NewAMQPBackend creates new AMQPBackend
func NewAMQPBackend(url string) (*AMQPBackend, error) {
conn, err := amqp.Dial(url)
if err != nil {
return nil, err
}
b := &AMQPBackend{conn: conn}
return b.Codec(NewGOBCodec()), nil
}
// Codec sets codec to encode/decode objects in queues. GOBCodec is default.
func (b *AMQPBackend) Codec(c Codec) *AMQPBackend {
b.codec = c
return b
}
// Put adds value to the end of a queue.
func (b *AMQPBackend) Put(queueName string, value interface{}) error {
data, err := b.codec.Marshal(value)
if err != nil {
return err
}
ch, err := b.conn.Channel()
if err != nil {
return err
}
defer ch.Close()
q, err := ch.QueueDeclare(
queueName, // name
true, // durable
true, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return err
}
return ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/octet-stream",
Body: data,
})
}
// Get removes the first element from a queue and put it in the value pointed to by v
func (b *AMQPBackend) Get(queueName string, v interface{}) error {
ch, err := b.conn.Channel()
if err != nil {
return err
}
defer ch.Close()
q, err := ch.QueueDeclare(
queueName, // name
true, // durable
true, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return err
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return err
}
d := <-msgs
return b.codec.Unmarshal(d.Body, v)
}
func (b *AMQPBackend) RemoveQueue(queueName string) error {
return nil
}