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