chirpnest/workers.go

82 lines
2.3 KiB
Go
Raw Normal View History

2019-05-05 13:29:28 +02:00
package main
import (
2019-05-06 04:54:24 +02:00
"encoding/json"
2019-05-05 13:29:28 +02:00
"log"
"strconv"
2019-05-06 04:54:24 +02:00
"github.com/streadway/amqp"
2019-05-05 13:29:28 +02:00
)
2019-05-06 04:54:24 +02:00
func MQGetMsgWorker(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, "MQGetMsgWorker["+strconv.Itoa(id)+"] : Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "MQGetMsgWorker["+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, "MQGetMsgWorker["+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, "MQGetMsgWorker["+strconv.Itoa(id)+"] : Failed to register a consumer")
for d := range m {
log.Printf("MQGetMsgWorker["+strconv.Itoa(id)+"] : Received a message: %s", string(d.Body))
err = json.Unmarshal(d.Body, &x)
logOnError(err, "MQGetMsgWorker["+strconv.Itoa(id)+"] : Can't unmarshal.\n"+string(d.Body))
if err == nil {
msgs <- x
}
}
log.Printf("MQGetMsgWorker[" + strconv.Itoa(id) + "] : Closing.")
}
func SQLCWMsgWorker(id int, msgs <-chan ChatWarsMessage, objIds chan<- int64) {
2019-05-05 13:29:28 +02:00
log.Printf("SQLCWMsgWorker[" + strconv.Itoa(id) + "] : Starting.")
for m := range msgs {
objId, err := putUnprocessedMsg(m)
2019-05-06 04:54:24 +02:00
logOnError(err, "SQLCWMsgWorker["+strconv.Itoa(id)+"] : Inserting message.")
if err == nil {
log.Printf("SQLCWMsgWorker["+strconv.Itoa(id)+"] : Message inserted (%d).\n", objId)
objIds <- objId
2019-05-05 13:29:28 +02:00
}
}
log.Printf("SQLCWMsgWorker[" + strconv.Itoa(id) + "] : Closing.")
}
func SQLIdentifyMsgWorker(id int, objIds <-chan int64) {
log.Printf("SQLIdentifyMsgWorker[" + strconv.Itoa(id) + "] : Starting.")
for objId := range objIds {
2019-05-06 04:54:24 +02:00
m, err := getMsg(objId)
logOnError(err, "SQLIdentifyMsgWorker["+strconv.Itoa(id)+"] : Retrieving message.")
if err == nil {
2019-05-06 04:56:59 +02:00
log.Printf("SQLIdentifyMsgWorker["+strconv.Itoa(id)+"] : Message retrieved\n%s\n", m.Text)
2019-05-06 04:54:24 +02:00
}
2019-05-05 13:29:28 +02:00
}
log.Printf("SQLIdentifyMsgWorker[" + strconv.Itoa(id) + "] : Closing.")
}