Created
April 1, 2023 03:01
-
-
Save argentinaluiz/bda13d2135b3aa83733bcc351d5aba95 to your computer and use it in GitHub Desktop.
Golang + RabbitMQ + Múltiplos consumers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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