Skip to content

Instantly share code, notes, and snippets.

@argentinaluiz
Created April 1, 2023 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save argentinaluiz/bda13d2135b3aa83733bcc351d5aba95 to your computer and use it in GitHub Desktop.
Save argentinaluiz/bda13d2135b3aa83733bcc351d5aba95 to your computer and use it in GitHub Desktop.
Golang + RabbitMQ + Múltiplos consumers
package queues
import (
"log"
"github.com/streadway/amqp"
)
var conn *amqp.Connection
func InitConnection() error {
var err error
conn, err = amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
return err
}
return nil
}
func CloseConnection() error {
if conn != nil {
return conn.Close()
}
return nil
}
func OpenChannel() (*amqp.Channel, error) {
if conn == nil {
return nil, fmt.Errorf("connection not initialized")
}
return conn.Channel()
}
// queues/report_handler.go
package queues
import (
"log"
"github.com/streadway/amqp"
)
func HandleReportQueue() error {
ch, err := OpenChannel()
if err != nil {
return err
}
defer ch.Close()
q, err := ch.QueueDeclare(
"report_queue",
false,
false,
false,
false,
nil,
)
if err != nil {
return err
}
msgs, err := ch.Consume(
q.Name,
"",
true,
false,
false,
false,
nil,
)
if err != nil {
return err
}
for msg := range msgs {
log.Printf("Received message: %s", msg.Body)
}
return nil
}
// main.go
package main
import (
"log"
"github.com/yourusername/project/queues"
)
func main() {
err := queues.InitConnection()
if err != nil {
log.Fatalf("Failed to initialize connection: %s", err)
}
defer queues.CloseConnection()
go queues.HandleReportQueue()
// handle other queues here
// wait for signal to exit
select {}
}
package main
import (
"log"
"github.com/seu_usuario/project/queues"
)
func main() {
err := queues.InitConnection()
if err != nil {
log.Fatalf("Failed to initialize connection: %s", err)
}
defer queues.CloseConnection()
go queues.HandleReportQueue()
// handle other queues here
// wait for signal to exit
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment