How do I produce and consume messages in RabbitMQ using Go?

In this tutorial, you'll learn how to produce and consume messages using RabbitMQ in Go. RabbitMQ is a robust messaging broker that facilitates communication between applications. We'll walk you through the steps necessary to set up a simple producer and consumer.

// Producer Example package main import ( "log" "github.com/streadway/amqp" ) func main() { conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") if err != nil { log.Fatalf("Failed to connect to RabbitMQ: %s", err) } defer conn.Close() ch, err := conn.Channel() if err != nil { log.Fatalf("Failed to open a channel: %s", err) } defer ch.Close() queue, err := ch.QueueDeclare( "test_queue", // name false, // durable false, // delete when unused false, // exclusive false, // no-wait nil, // arguments ) if err != nil { log.Fatalf("Failed to declare a queue: %s", err) } body := "Hello RabbitMQ" err = ch.Publish( "", // exchange queue.Name, // routing key false, // mandatory false, // immediate amqp.Publishing{ ContentType: "text/plain", Body: []byte(body), }) if err != nil { log.Fatalf("Failed to publish a message: %s", err) } log.Printf("Sent message: %s", body) } // Consumer Example package main import ( "log" "github.com/streadway/amqp" ) func main() { conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") if err != nil { log.Fatalf("Failed to connect to RabbitMQ: %s", err) } defer conn.Close() ch, err := conn.Channel() if err != nil { log.Fatalf("Failed to open a channel: %s", err) } defer ch.Close() q, err := ch.QueueDeclare( "test_queue", // name false, // durable false, // delete when unused false, // exclusive false, // no-wait nil, // arguments ) if err != nil { log.Fatalf("Failed to declare a queue: %s", err) } msgs, err := ch.Consume( q.Name, // queue "", // consumer true, // auto-ack false, // exclusive false, // no-local false, // no-wait nil, // args ) if err != nil { log.Fatalf("Failed to register a consumer: %s", err) } go func() { for d := range msgs { log.Printf("Received a message: %s", d.Body) } }() log.Printf("Waiting for messages. To exit press CTRL+C") select {} }

RabbitMQ Go messaging producer consumer tutorial