\$\begingroup\$
\$\endgroup\$
I have two sender-receivers. The first is written on Python and the second is on Golang. I used official sources of RabbitMQ documentation here and here.
Python code:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
num = int(body[5:])
num = num + 1
channel.basic_publish(exchange='',
routing_key='hello',
body='hello'+str(num))
channel.basic_consume(callback,
queue='hello',
no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
connection.close()
Golang receiver-sender:
package main
import (
"log"
"strconv"
"fmt"
"github.com/streadway/amqp"
)
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
q, err := ch.QueueDeclare(
"hello", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
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 {
log.Printf("Received a message: %s", d.Body)
s := string(d.Body)
num, _ := strconv.ParseInt(s[5:], 0, 64)
num++
body := fmt.Sprintf("hello%d", num)
err = ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing {
ContentType: "text/plain",
Body: []byte(body),
})
failOnError(err, "Failed to publish a message")
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
What can be improved here? May be I can use non-default exchange
here? Are both pieces of my code working asynchronously?
default