This repository has been archived by the owner on Jan 29, 2024. It is now read-only.
/
main.go
83 lines (79 loc) · 1.53 KB
/
main.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
package main
import (
"context"
"github.com/peizhong/letsgo/internal"
"github.com/streadway/amqp"
"log"
)
func subscribe(addr, queue string) (ch *amqp.Channel, msgs <-chan amqp.Delivery, closer func()) {
conn, err := amqp.Dial(addr)
if err != nil {
log.Fatal(err)
}
// open a channel
ch, err = conn.Channel()
if err != nil {
log.Fatal(err)
}
q, err := ch.QueueDeclare(
"hello", // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Fatal(err)
}
err = ch.Qos(
1, // prefetch count
0, // prefetch size
false, // global
)
if err != nil {
log.Fatal(err)
}
msgs, err = ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack, call Delivery.Ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
return ch, msgs, func() {
ch.Close()
conn.Close()
}
}
func recv(ctx context.Context, exit chan struct{}) {
ch, msgs, closer := subscribe("amqp://guest:guest@193.112.41.28:5672/", "hello")
loop:
for {
select {
case d := <-msgs:
err := ch.Publish(
"", // exchange
d.ReplyTo, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
CorrelationId: d.CorrelationId,
Body: []byte("gotcha"),
})
if err == nil {
d.Ack(false)
}
case <-ctx.Done():
break loop
}
}
closer()
exit <- struct{}{}
}
func main() {
internal.HostWithContext(recv)
}