V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
mine21
V2EX  ›  Go 编程语言

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

  •  
  •   mine21 · 2020-05-11 16:42:07 +08:00 · 2201 次点击
    这是一个创建于 1453 天前的主题,其中的信息可能已经有所发展或是发生改变。
    现在按照晚上教程写了个代码,功能是可以啦,但是 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
    }
    3 条回复    2020-05-12 15:10:10 +08:00
    Gakho
        1
    Gakho  
       2020-05-11 18:55:38 +08:00
    断开了连接这种 err 在你的 go func 应该能取到的,不用其他库的话就自己做重试
    zpfhbyx
        2
    zpfhbyx  
       2020-05-11 19:00:35 +08:00
    你 rabbitmq 有开 heartbeat 么
    mine21
        3
    mine21  
    OP
       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.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2277 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 15:20 · PVG 23:20 · LAX 08:20 · JFK 11:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.