2024-09-05 11:50:34 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2024-09-06 16:54:35 +00:00
|
|
|
"listener/event"
|
2024-09-05 11:50:34 +00:00
|
|
|
"log"
|
|
|
|
"math"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// try to connect to rabbitmq
|
|
|
|
rabbitConn, err := connect()
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
defer rabbitConn.Close()
|
|
|
|
log.Println("Connected to RabbitMQ")
|
|
|
|
|
|
|
|
// start listening for messages
|
2024-09-06 16:54:35 +00:00
|
|
|
log.Println("Listening for and consuming RabbitMQ messages...")
|
2024-09-05 11:50:34 +00:00
|
|
|
// create consumer
|
|
|
|
|
2024-09-06 16:54:35 +00:00
|
|
|
consumer, err := event.NewConsumer(rabbitConn)
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
|
|
|
|
2024-09-05 11:50:34 +00:00
|
|
|
// watch the queue and consume events
|
2024-09-06 16:54:35 +00:00
|
|
|
err = consumer.Listen([]string{"log.INFO", "log.WARNING", "log.ERROR"})
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
2024-09-05 11:50:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func connect() (*amqp.Connection, error) {
|
|
|
|
var counts int64
|
|
|
|
var connection *amqp.Connection
|
|
|
|
|
|
|
|
// don't continue until rabbit is ready
|
|
|
|
for {
|
2024-09-06 16:54:35 +00:00
|
|
|
c, err := amqp.Dial("amqp://guest:guest@rabbitmq") // XXX: credentials
|
2024-09-05 11:50:34 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Println("RabbitMQ not yet ready...")
|
|
|
|
counts++
|
|
|
|
} else {
|
|
|
|
connection = c
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
if counts > 5 {
|
|
|
|
fmt.Println(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
backOff := time.Duration(math.Pow(float64(counts), 2) * float64(time.Second))
|
|
|
|
log.Println("backing off...")
|
|
|
|
time.Sleep(backOff)
|
|
|
|
}
|
|
|
|
|
|
|
|
return connection, nil
|
|
|
|
}
|