如何使rabbitmq消费者超时?

I have rabbitmq consuming the queue but once client is subscribed it stays consuming queue forever. Is there a timeout to declare and exit i.e. after queue is empty ?

 msgs, err := ch.Consume(
                q.Name, // queue
                "",     // consumer
                true,   // auto-ack
                false,  // exclusive
                false,  // no-local
                false,  // no-wait
                nil,    // args
        )
for msg := range msgs { 
                log.Printf("Received message with message: %s", msg.Body)
}

You can use the standard Go pattern for timing out.

Here is a working example.

const duration = 3 * time.Second
timer := time.NewTimer(duration)
for {
    select {
    case d := <-msgs:
        timer.Reset(duration)
        fmt.Printf("Received a message: %s
", d.Body)
    case <- timer.C:
        fmt.Println("Timeout !")
        os.Exit(1)
    }
}

It probably needs some polishing, e.g. I suppose it would be better to stop the timer when you receive the message and enable it again when you are done processing it, but this should get you started.