To publish messages, create a connection using rabbitmq.NewConn and then create a publisher using rabbitmq.NewPublisher.
Key behaviors:
- Exchanges are not declared by default; use
rabbitmq.WithPublisherOptionsExchangeDeclare to ensure the exchange exists. - Use
publisher.Publish to send messages. You can specify the body, routing keys, and content type.
Note: Always close your publishers and consumers before closing the connection.
conn, err := rabbitmq.NewConn(
"amqp://guest:guest@localhost",
rabbitmq.WithConnectionOptionsLogging,
)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
publisher, err := rabbitmq.NewPublisher(
conn,
rabbitmq.WithPublisherOptionsLogging,
rabbitmq.WithPublisherOptionsExchangeName("events"),
rabbitmq.WithPublisherOptionsExchangeDeclare,
)
if err != nil {
log.Fatal(err)
}
defer publisher.Close()
err = publisher.Publish(
[]byte("hello, world"),
[]string{"my_routing_key"},
rabbitmq.WithPublishOptionsContentType("application/json"),
rabbitmq.WithPublishOptionsExchange("events"),
)
if err != nil {
log.Println(err)
}