SoFunction
Updated on 2025-03-05

Golang rabbitMQ producer consumer implementation example

consumer

package main
import (
	"fmt"
	"/streadway/amqp"
)
func failOnError(err error, msg string) {
	if err != nil {
		("%s: %s", msg, err)
	}
}
// Only operate on servers where rabbitmq is installedfunc main() {
	conn, err := ("amqp://mquser:[email protected]/toutiao")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer ()
	ch, err := ()
	failOnError(err, "Failed to open a channel")
	defer ()
	q, err := (
		"", // Queue name		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	failOnError(err, "Failed to declare a queue")
	msgs, err := (
		, 		// queue
		"toutiao",     // consumer
		true,   // auto-ack, true consumption disappears		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	failOnError(err, "Failed to register a consumer")
	forever := make(chan bool)
	go func() {
		for d := range msgs {
			(("Returned message:%s",))
		}
	}()
	("[*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

Producer

body: message body

package main
import (
	"/streadway/amqp"
	"log"
)
func failOnError(err error, msg string) {
	if err != nil {
		("%s: %s", msg, err)
	}
}
// Only operate on servers where rabbitmq is installedfunc main() {
	conn, err := ("amqp://mquser:[email protected]/toutiao")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer ()
	ch, err := ()
	failOnError(err, "Failed to open a channel")
	defer ()
	q, err := (
	"",   // name
		false, // durable
		false, // delete when unused
		false, // exclusive
		false, // no-wait
		nil, // arguments
)
	failOnError(err, "Failed to declare a queue")
	body := "Hello World!"  //Send message	err = (
	"",         // exchange
		, // routing key
		false,  // mandatory
		false,  // immediate
		{
		ContentType: "text/plain",
			Body:        []byte(body),
		})
	(" [x] Sent %s", body)
	failOnError(err, "Failed to publish a message")
}

The above is the detailed content of the Golang rabbitMQ producer and consumer implementation example analysis. For more information about Golang rabbitMQ producer and consumer, please follow my other related articles!