Abel'Blog

我干了什么?究竟拿了时间换了什么?

0%

go-rabbit-mq

简介

rabbitmq-logo

最近还需要使用rabbitmq需要使用golang来实现。

如何创建一个连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

encodedPassword := url.QueryEscape(viper.GetString("rabbitmq.password"))
// SSL,
tlsConfig := &tls.Config{InsecureSkipVerify: true}
dsn := fmt.Sprintf(
"amqps://%s:%s@%s:%d/",
viper.GetString("rabbitmq.user"),
encodedPassword,
viper.GetString("rabbitmq.host"),
viper.GetInt("rabbitmq.port"),
)
conn, err := amqp.DialTLS(dsn,tlsConfig)

if err != nil {
logrus.Warnf("GenerateMQ fail err: %v", err.Error())
return nil, err
}

logrus.Infoln("GenerateMQ success!")
return conn, nil

发送

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

func main() {
conn, err := mqutils.GenerateMQ()
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(
"hello", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

body := "Hello World!"
err = ch.PublishWithContext(ctx,
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
failOnError(err, "Failed to publish a message")
logrus.Printf(" [x] Sent %s\n", body)
}

接受消息

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

func main() {
conn, err := mqutils.GenerateMQ()
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(
"hello", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")

msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")

var forever chan struct{}

go func() {
for d := range msgs {
logrus.Printf("Received a message: %s", d.Body)
}
}()

logrus.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}

参考