104 lines
2.0 KiB
Go
104 lines
2.0 KiB
Go
package rabbitmq
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"git.umbach.dev/app-idea/rest-api/modules/config"
|
|
"git.umbach.dev/app-idea/rest-api/modules/structs"
|
|
log "github.com/sirupsen/logrus"
|
|
"github.com/streadway/amqp"
|
|
)
|
|
|
|
var Conn *amqp.Connection
|
|
var Channel *amqp.Channel
|
|
|
|
var MailQueue amqp.Queue
|
|
var PictureQueue amqp.Queue
|
|
|
|
func getConnectionString() string {
|
|
cfg := &config.Cfg.RabbitMq
|
|
|
|
return fmt.Sprintf("amqp://%s:%s@%s/", cfg.Username, cfg.Password, cfg.Host)
|
|
}
|
|
|
|
func Init() {
|
|
conn, err := amqp.Dial(getConnectionString())
|
|
|
|
if err != nil {
|
|
log.Fatalln("Failed to connect to RabbitMQ", err)
|
|
}
|
|
|
|
Conn = conn
|
|
|
|
ch, err := conn.Channel()
|
|
|
|
if err != nil {
|
|
log.Fatalln("Failed to open a channel", err)
|
|
}
|
|
|
|
Channel = ch
|
|
|
|
log.Debug("RabbitMQ connected")
|
|
|
|
declareQueue(ch, "mails", &MailQueue)
|
|
declareQueue(ch, "pictures", &PictureQueue)
|
|
}
|
|
|
|
func declareQueue(channel *amqp.Channel, name string, queue *amqp.Queue) {
|
|
q, err := channel.QueueDeclare(
|
|
name, // name
|
|
true, // durable
|
|
false, // delete when unused
|
|
false, // exclusive
|
|
false, // no-wait
|
|
nil, // arguments
|
|
)
|
|
|
|
if err != nil {
|
|
log.Fatalln("Failed to declare a queue", err)
|
|
}
|
|
|
|
*queue = q
|
|
}
|
|
|
|
func Publish(queue amqp.Queue, body string) {
|
|
log.Infoln("publish queue name", queue.Name)
|
|
|
|
err := Channel.Publish(
|
|
"", // exchange
|
|
queue.Name, // routing key
|
|
false, // mandatory
|
|
false, // immediate
|
|
amqp.Publishing{
|
|
DeliveryMode: amqp.Persistent,
|
|
ContentType: "application/json",
|
|
Body: []byte(body),
|
|
})
|
|
|
|
if err != nil {
|
|
log.Fatalln("Failed to publish a message", err)
|
|
}
|
|
}
|
|
|
|
func PublishMail(mailMessage structs.RabbitmqMailMessage) {
|
|
reqBody, err := json.MarshalIndent(&mailMessage, "", "\t")
|
|
|
|
if err != nil {
|
|
log.Infoln("error reqBody", err)
|
|
}
|
|
|
|
Publish(MailQueue, string(reqBody))
|
|
}
|
|
|
|
func PublishPicture(pictureMessage structs.RabbitmqPictureMessage) {
|
|
reqBody, err := json.MarshalIndent(&pictureMessage, "", "\t")
|
|
|
|
if err != nil {
|
|
log.Infoln("error reqBody", err)
|
|
}
|
|
|
|
Publish(PictureQueue, string(reqBody))
|
|
log.Debugln("rabbitmq publicPicture")
|
|
}
|