RabbitMQ connection with Pika - Preventing connection reset by peer

118 views
Skip to first unread message

Robin Bonnin

unread,
Sep 29, 2021, 9:38:50 PM9/29/21
to Pika
Hi!

I am currently trying to implement a basic queue for my django app.
My Django app is only publishing to the queue when there is a request on my REST endpoint.

There are 3 cases I tried:
  1. Start the connection when the server starts and then reuse it without closing the connection
  2. Start the connection when the server start and then reuse it but closing the connection
  3. Create a new connection each time I want to publish a message (I don't like it because of the overhead)

Here are my results:
  1. After some time (which seems to be the heartbeat timere), the connection is marked as reset by peer
  2. After the first request, the channel is marked as closed.
  3. This works but I don't like it as I have to reconnect for each request.


Here is my code for case 1:

import pika
from decouple import config
from django.conf import settings


class CloudAMQPConsumerMixin:
url = settings.CLOUD_AMQP_URL

def __init__(self, queue: str) -> None:
self.queue = queue
self._connect()

def _connect(self):

params = pika.URLParameters(self.url)
params.heartbeat = 10
params.blocked_connection_timeout = 5
self.connection = pika.BlockingConnection(params)

def send_message(self, text):

self.channel = self.connection.channel() # start a channel
self.channel.queue_declare(queue=self.queue)
self.channel.basic_publish(exchange="", routing_key=self.queue, body=text)

print(f" [x] Sent {text}")

ampq_publisher = CloudAMQPConsumerMixin(queue="notification")

In my endpoint:

def list(self, request, *args, **kwargs):
import json

from libraries.queue.rabbitmq import ampq_publisher

print("Send a message to the queue!")
notification_message = {}
notification_message["user"] = str(request.user)
notification_message["profile"] = str(request.user.profile)
ampq_publisher.send_message(json.dumps(notification_message))
return Response(status=status.HTTP_200_OK)


I could not find how to format, let me know if there is.

Thank you for your help!



Reply all
Reply to author
Forward
0 new messages