-
Notifications
You must be signed in to change notification settings - Fork 1
/
rabitmq.go
65 lines (58 loc) · 1.42 KB
/
rabitmq.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
package main
import (
"context"
"flag"
"fmt"
"github.com/streadway/amqp"
)
var rabitPort = "32814"
var url = flag.String("url", "amqp://guest:[email protected]:"+rabitPort+"/", "Amqp url for both the publishe and subscriber")
type Rabitmq struct {
conn *amqp.Connection
channel *amqp.Channel
}
func NewRabitmq(ctx context.Context) (*Rabitmq, error) {
conn, err := amqp.Dial(*url)
if err != nil {
fmt.Println(err)
}
ch, err := conn.Channel()
if err != nil {
fmt.Println(err)
}
return &Rabitmq{
conn: conn,
channel: ch,
}, nil
}
func (q *Rabitmq) EnqueueMessage(ctx context.Context, targetId uint64, msg []byte) error {
_, err := q.channel.QueueDeclare(fmt.Sprintf("user_%d", targetId), true, false, false, true, nil)
if err != nil {
return err
}
return q.channel.Publish("", fmt.Sprintf("user_%d", targetId), true, false, amqp.Publishing{
Body: msg,
})
}
func (q *Rabitmq) ConsumeMessage(ctx context.Context, targetId uint64) (<-chan []byte, error) {
_, err := q.channel.QueueDeclare(fmt.Sprintf("user_%d", targetId), true, false, false, true, nil)
if err != nil {
return nil, err
}
delivery, err := q.channel.Consume(fmt.Sprintf("user_%d", targetId), "", true, false, false, true, nil)
if err != nil {
return nil, err
}
messages := make(chan []byte)
go func() {
for {
select {
case <-ctx.Done():
return
case msg := <-delivery:
messages <- msg.Body
}
}
}()
return messages, nil
}