0

I know how to pass string, dictionaries and json to rmq but how can I pass simple integers to rmq?

My send.py file looks like this

import sys
import json

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)

message = {'id': 7, 'name': 'Akshat'}
channel.basic_publish(exchange='',
                      routing_key='task_queue',
                      body=json.dumps(message),
                      properties=pika.BasicProperties(
                         delivery_mode = 2, # make message persistent
                      ))
print(" [x] Sent %r" % message)
connection.close()

And receive.py looks like this

import time
import json

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)
print(' [*] Waiting for messages. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % json.loads(body))
    #print(body['id'])
    print(" [x] Done")
    ch.basic_ack(delivery_tag = method.delivery_tag)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
                      queue='task_queue')

channel.start_consuming()
akshatj7
  • 1
  • 2
  • The body being passed is`bytes` so you will need to convert that to `int`. – metatoaster May 23 '22 at 07:31
  • how to convert it to int ? – akshatj7 May 23 '22 at 07:34
  • You will note that you already have a `json.dumps` in `basic_publish` serving as the encoder and `json.loads` serving as the decoder in the `callback` for `basic_consume` - same thing, you need to encode the integer to bytes and then decode those bytes back into an integer in the corresponding methods, as per the [linked thread](https://stackoverflow.com/questions/67330892/how-to-send-integer-parameter-to-rabbitmq), using `to_bytes` and `from_bytes`. – metatoaster May 23 '22 at 07:36

0 Answers0