新学 go,求帮忙,连接 rabbitmq,心跳检测重试问题 作用: mq 客户端监听队列,获取队列消息

2020-05-11 16:42:07 +08:00
 mine21
现在按照晚上教程写了个代码,功能是可以啦,但是 mq 正常情况,连接成功。但是 mq 挂了,再启动 mq, 我写的这个客户端就监听不到了,连接已经挂掉了,怎么心跳检测重新发起连接那,
求指点下,新学 go,有点懵



目前的客户端照着网上的教程写的
package main

import (
"log"

"github.com/streadway/amqp"
)

func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}

// 只能在安装 rabbitmq 的服务器上操作
func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
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")

forever := make(chan bool)

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

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
2211 次点击
所在节点    Go 编程语言
3 条回复
Gakho
2020-05-11 18:55:38 +08:00
断开了连接这种 err 在你的 go func 应该能取到的,不用其他库的话就自己做重试
zpfhbyx
2020-05-11 19:00:35 +08:00
你 rabbitmq 有开 heartbeat 么
mine21
2020-05-12 15:10:10 +08:00
最后用这个单写了个 重试
amqp:

func (*Connection) NotifyClose

func (c *Connection) NotifyClose(receiver chan *Error) chan *Error

NotifyClose registers a listener for close events either initiated by an error accompanying a connection.close method or by a normal shutdown.

On normal shutdowns, the chan will be closed.

To reconnect after a transport or protocol error, register a listener here and re-run your setup process.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/670609

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX