Pada tutorial sebelumnya kita telah belajar cara menginstal RabbitMQ mengunakan docker compose di local komputer.
Ditutorial kali ini kita akan belajar bagaimana cara publish pesan ke RabbitMQ menggunakan bahasa golang.
Untuk mengikuti tutorial ini pastikan bahwa Anda sudah menginstall RabbitMQ dan juga sudah menginstall Golang di local computer Anda.
Jika Anda belum menginstall Golang, Anda bisa membacanya di dokumentasi instalasi bahasa Go.
Perhatikan kode dibawah ini, buat dua buah file dengan nama publisher.go dan konsumer.go
package mainimport (
"log""github.com/streadway/amqp"
)func errorWrapper(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
errorWrapper(err, "Failed to connect rabbitmq")
defer conn.Close()ch, err := conn.Channel()
errorWrapper(err, "Failed to open a channel")
defer ch.Close()q, err := ch.QueueDeclare(
"golang-queue", //name
false, // durable
false, //delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
errorWrapper(err, "Failed to declare a queue")body := "Hi halovina, keep in touch"
err = ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immadiate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})errorWrapper(err, "Failed to publish message")
log.Printf("Sending message success: %s", body)}
package mainimport (
"log""github.com/streadway/amqp"
)func errorWrapper(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
errorWrapper(err, "Failed to connect rabbitmq")
defer conn.Close()ch, err := conn.Channel()
errorWrapper(err, "Failed to open a channel")
defer ch.Close()q, err := ch.QueueDeclare(
"golang-queue", //name
false, // durable
false, //delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
errorWrapper(err, "Failed to declare a queue")msg, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
errorWrapper(err, "Failed to register a consumer")forever := make(chan bool)
go func() {
for d := range msg {
log.Printf("received as message: %s", d.Body)
}
}()
log.Printf("waiting for message. to exit press CTRL+C")
<-forever
}
sending message go rabbitmq