chirpnest/mq.go

55 lines
1.4 KiB
Go
Raw Normal View History

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 11:15:33 +02:00
func MQGetMsgWorker(id int, msgs chan<- ChatWarsMessage) {
2019-05-04 10:57:24 +02:00
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 11:15:33 +02:00
failOnError(err, "MQGetMsgWorker["+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 11:15:33 +02:00
failOnError(err, "MQGetMsgWorker["+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 11:15:33 +02:00
failOnError(err, "MQGetMsgWorker["+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 11:15:33 +02:00
failOnError(err, "MQGetMsgWorker["+strconv.Itoa(id)+"] : Failed to register a consumer")
2019-05-04 10:57:24 +02:00
for d := range m {
2019-05-04 11:15:33 +02:00
log.Printf("MQGetMsgWorker["+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:15:33 +02:00
logOnError(err, "MQGetMsgWorker["+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 11:15:33 +02:00
log.Printf("MQGetMsgWorker[" + strconv.Itoa(id) + "] : Closing.")
2019-05-03 05:58:36 +02:00
}