Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reduce memory usage of Connection #160

Merged
merged 1 commit into from
Dec 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions librabbitmq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def __init__(self, host='localhost', userid='guest', password='guest',
client_properties=client_properties,
)
self.channels = {}
self._avail_channel_ids = array('H', xrange(self.channel_max, 0, -1))
self._used_channel_ids = array('H')
if not lazy:
self.connect()

Expand Down Expand Up @@ -247,15 +247,21 @@ def _remove_channel(self, channel):
pass
self.channels.pop(channel.channel_id, None)
self.callbacks.pop(channel.channel_id, None)
self._avail_channel_ids.append(channel.channel_id)
try:
self._used_channel_ids.remove(channel.channel_id)
except ValueError:
# channel id already removed
pass

def _get_free_channel_id(self):
try:
return self._avail_channel_ids.pop()
except IndexError:
raise ConnectionError(
'No free channel ids, current=%d, channel_max=%d' % (
len(self.channels), self.channel_max))
for channel_id in range(1, self.channel_max):
if channel_id not in self._used_channel_ids:
self._used_channel_ids.append(channel_id)
return channel_id

raise ConnectionError(
'No free channel ids, current=%d, channel_max=%d' % (
len(self.channels), self.channel_max))

def close(self):
try:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import socket
import unittest
from array import array

from librabbitmq import Message, Connection, ConnectionError, ChannelError
TEST_QUEUE = 'pyrabbit.testq'
Expand Down Expand Up @@ -122,6 +123,15 @@ def cb(x):
self.connection.drain_events(timeout=0.1)
self.assertEqual(len(messages), 1)

def test_get_free_channel_id(self):
self.connection._used_channel_ids = array('H')
assert self.connection._get_free_channel_id() == 1

def test_get_free_channel_id__channels_full(self):
self.connection._used_channel_ids = array('H', range(1, self.connection.channel_max))
with self.assertRaises(ConnectionError):
self.connection._get_free_channel_id()

def tearDown(self):
if self.channel and self.connection.connected:
self.channel.queue_purge(TEST_QUEUE)
Expand Down