-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrabbitmq.go
115 lines (93 loc) · 2.09 KB
/
rabbitmq.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
type Rabbitmq struct {
hostname string
user string
password string
port string
queue string
}
func (r *Rabbitmq) RabbitMqGetMessages(bb *Busyboi) {
conn, err := amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%s/", r.user, r.password, r.hostname, r.port))
if err != nil {
log.Panicf("Failed to connect to queue: %s", err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Panicf("Failed to create channel: %s", err)
}
defer ch.Close()
q, err := ch.QueueDeclare(
r.queue, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Panicf("Failed to declare queue: %s", 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 {
log.Panicf("Failed to consume: %s", err)
}
for {
bb.queueMsgs <- <-msgs
}
}
func (r *Rabbitmq) RabbitMqAddMessages(job JobConfig) {
conn, err := amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%s/", r.user, r.password, r.hostname, r.port))
if err != nil {
log.Panicf("Failed to connect to queue: %s", err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Panicf("Failed to create channel: %s", err)
}
defer ch.Close()
q, err := ch.QueueDeclare(
r.queue, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Panicf("Failed to declare queue: %s", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
body, _ := json.Marshal(job)
err = ch.PublishWithContext(ctx,
"", // exchange
q.Name, // routing key
false, // mandatory
false,
amqp.Publishing{
DeliveryMode: amqp.Persistent,
ContentType: "text/plain",
Body: body,
})
if err != nil {
log.Panicf("Failed to publish: %s", err)
}
}