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
117
118
119
120
121
122
123
|
package main
import (
"fmt"
"log"
"math/rand"
"os"
"strings"
"time"
"github.com/streadway/amqp"
)
func main() {
account := os.Getenv("pg_mq_user")
password := os.Getenv("pg_mq_pass")
hosts := strings.Split(os.Getenv("pg_mq_hosts"), ",")
port := os.Getenv("pg_mq_port")
vhost := os.Getenv("pg_mq_vhost")
conn, err := amqp.Dial(fmt.Sprintf(
"amqp://%s:%s@%s:%s/%s",
account, password,
hosts[rand.Intn(len(hosts))], port, vhost,
))
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
q, err := ch.QueueDeclare(
"sample", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
cch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer cch.Close()
failOnError(err, "Failed to declare a queue")
go func() {
num := 0
for true {
body := fmt.Sprintf("hello:%d", num)
err = cch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
failOnError(err, "Failed to publish a message")
time.Sleep(1 * time.Second)
num++
}
}()
cch2, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer cch2.Close()
msgs1, err := cch2.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
forever := make(chan bool)
go func() {
for d := range msgs1 {
log.Printf("Received a message(1): %s", d.Body)
go func(msg amqp.Delivery) {
time.Sleep(2 * time.Second)
fmt.Println("PRE d.Nack")
d.Nack(false, true)
fmt.Println("POST d.Nack")
}(d)
time.Sleep(1 * time.Second)
}
fmt.Println("end consume msg1")
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
msgs2, err := ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
go func() {
for d := range msgs2 {
log.Printf("Received a message(2): %s", d.Body)
time.Sleep(1 * time.Second)
go func(msg amqp.Delivery) {
time.Sleep(1 * time.Second)
fmt.Println("PRE d.Ack")
msg.Ack(false)
fmt.Println("POST d.Ack")
}(d)
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
|