Skip to content

Commit

Permalink
Use a persistent ampq connection when publishing
Browse files Browse the repository at this point in the history
  • Loading branch information
sillyfrog committed Feb 25, 2023
1 parent 4b19c70 commit 2e6d91f
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions src/socketio/asyncio_aiopika_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ def __init__(self, url='amqp://guest:guest@localhost:5672//',
'(Run "pip install aio_pika" in your '
'virtualenv).')
self.url = url
self._lock = asyncio.Lock()
self._sender_connection_cache = None
self.listener_connection = None
self.listener_channel = None
self.listener_queue = None
Expand All @@ -52,6 +54,27 @@ def __init__(self, url='amqp://guest:guest@localhost:5672//',
async def _connection(self):
return await aio_pika.connect_robust(self.url)

async def _sender_connection(self):
if self._sender_connection_cache is None:
async with self._lock:
if self._sender_connection_cache is None:
connection = await self._connection()
channel = await connection.channel()
exchange = await channel.declare_exchange(
self.channel, aio_pika.ExchangeType.FANOUT
)
queue = await channel.declare_queue(
durable=False, arguments={"x-expires": 300000}
)
self._sender_connection_cache = {
"connection": connection,
"channel": channel,
"exchange": exchange,
"queue": queue,
}

return self._sender_connection_cache

async def _channel(self, connection):
return await connection.channel()

Expand All @@ -66,13 +89,13 @@ async def _queue(self, channel, exchange):
return queue

async def _publish(self, data):
connection = await self._connection()
channel = await self._channel(connection)
exchange = await self._exchange(channel)
await exchange.publish(
aio_pika.Message(body=pickle.dumps(data),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT),
routing_key='*'
full_connection = await self._sender_connection()
await full_connection["exchange"].publish(
aio_pika.Message(
body=pickle.dumps(data),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
),
routing_key="*",
)

async def _listen(self):
Expand Down

0 comments on commit 2e6d91f

Please sign in to comment.