chirpnest/mq.go
2019-05-04 17:02:44 +08:00

55 lines
1.3 KiB
Go

package main
import (
"encoding/json"
"log"
"strconv"
"github.com/streadway/amqp"
)
func MQGetMsg(id int, msgs chan<- ChatWarsMessage) {
var x ChatWarsMessage
conn, err := amqp.Dial("amqp://" + cfg.Rabbit.User + ":" + cfg.Rabbit.Password + "@" + cfg.Rabbit.Host + "/" + cfg.Rabbit.Queue)
failOnError(err, "MQGetMsg["+strconv.Itoa(id)+"] : Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "MQGetMsg["+strconv.Itoa(id)+"] : Failed to open a channel")
defer ch.Close()
q, err := ch.QueueDeclare(
"msg", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "MQGetMsg["+strconv.Itoa(id)+"] : Failed to declare a queue")
m, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "MQGetMsg["+strconv.Itoa(id)+"] : Failed to register a consumer")
for d := range m {
log.Printf("MQGetMsg["+strconv.Itoa(id)+"] : Received a message: %s", string(d.Body))
if err = json.Unmarshal(d.Body, &x); err != nil {
logOnError(err, "MQGetMsg["+strconv.Itoa(id)+"] : Can't unmarshal.\n"+string(d.Body))
} else {
msgs <- x
}
}
log.Printf("MQGetMsg[" + strconv.Itoa(id) + "] : Closing.")
}