本文整理汇总了Python中pika.adapters.tornado_connection.TornadoConnection.channel方法的典型用法代码示例。如果您正苦于以下问题:Python TornadoConnection.channel方法的具体用法?Python TornadoConnection.channel怎么用?Python TornadoConnection.channel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pika.adapters.tornado_connection.TornadoConnection
的用法示例。
在下文中一共展示了TornadoConnection.channel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
#all the following functions precede in order starting with connect
def connect(self):
try:
logger = logging.getLogger('rmq_tornado')
credentials = pika.PlainCredentials(RMQ_USER, RMQ_PWD)
param = pika.ConnectionParameters(host=RMQ_HOST, port=RMQ_PORT, credentials=credentials)
self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
except Exception as e:
logger.error('Something went wrong... %s', e)
def on_connected(self, connection):
"""When we are completely connected to rabbitmq this is called"""
logger.info('Succesfully connected to rabbitmq')
#open a channel
self.connection.channel(self.on_channel_open)
def on_channel_open(self, new_channel):
"""When the channel is open this is called"""
logging.info('Opening channel to rabbitmq')
global channel
channel = new_channel
示例2: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, username='guest', exchange_name='ws', password='guest', host='localhost', port=5672, virtual_host='/'):
self.exchange_name = exchange_name
# Options
self.username = username
self.password = password
self.host = host
self.port = port
self.virtual_host = virtual_host
# Default values
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
def connect(self):
if self.connecting:
pika.log.info('PikaClient: Already connecting to RabbitMQ')
return
pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672')
self.connecting = True
credentials = pika.PlainCredentials(self.username, self.password)
param = pika.ConnectionParameters(host=self.host,
port=self.port,
virtual_host=self.virtual_host,
credentials=credentials)
self.connection = TornadoConnection(param,
on_open_callback=self.on_connected)
self.connection.add_on_close_callback(self.on_closed)
def on_connected(self, connection):
pika.log.info('PikaClient: Connected to RabbitMQ on localhost:5672')
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
pika.log.info('PikaClient: Channel Open, Declaring Exchange')
self.channel = channel
self.channel.exchange_declare(exchange=self.exchange_name,
type="direct",
callback=self.on_exchange_declared)
def on_exchange_declared(self, frame):
pika.log.info('PikaClient: Exchange Declared, Ready for declaring Queues')
def on_basic_cancel(self, frame):
pika.log.info('PikaClient: Basic Cancel Ok')
# If we don't have any more consumer processes running close
self.connection.close()
def on_closed(self, connection):
# We've closed our pika connection so stop the demo
tornado.ioloop.IOLoop.instance().stop()
示例3: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, io_loop):
self.io_loop = io_loop
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
self.event_listeners = set([])
def connect(self):
if self.connecting:
return
self.connecting = True
self.connection = TornadoConnection(on_open_callback=self.on_connected)
self.connection.add_on_close_callback(self.on_closed)
def on_connected(self, connection):
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
self.channel = channel
channel.queue_declare(queue="plase", durable=True, callback=self.on_queue_declared)
def on_queue_declared(self, frame):
self.channel.basic_consume(self.on_message, queue="plase")
def on_closed(self, connection):
self.io_loop.stop()
def on_message(self, channel, method, header, body):
self.notify_listeners(body)
def notify_listeners(self, event_obj):
event_json = json.dumps(event_obj)
for listener in self.event_listeners:
listener.write_message(event_json)
def add_event_listener(self, listener):
self.event_listeners.add(listener)
def remove_event_listener(self, listener):
try:
self.event_listeners.remove(listener)
except KeyError:
pass
示例4: AMQPClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class AMQPClient(object):
"Connect to RabbitMQ and create a channel"
def __init__(self, on_msg_callback=None, oid=None, io_loop=None,
on_channel_created=None):
self.oid = oid or options.oid
self.io_loop = io_loop or IOLoop.instance()
self.on_msg_callback = on_msg_callback
self.connection = None
self.channel = None
self._on_channel_created = on_channel_created
self.checker = PeriodicCallback(self._check_connection, 1000)
def connect(self):
"Connect to RabbitMQ"
log.debug("Connecting to RabbitMQ")
if self.connection:
return
self.connection = TornadoConnection(
get_conn_params(),
self.on_connected,
custom_ioloop=self.io_loop)
def on_connected(self, connection):
"Create a channel just after connected"
log.debug("%s is established" % connection)
self.connection.channel(self.on_channel_created)
self.checker.start()
def on_channel_created(self, channel):
"Implement in subclasses"
log.debug("%s is established" % channel)
self.channel = channel
if self._on_channel_created:
self._on_channel_created(channel)
def _check_connection(self):
"Restablish connection to server if we lost it"
if self.connection:
try:
self.connection.socket.fileno()
except socket.error, exc:
log.debug("lost connection to RabbitMQ, %s" % str(exc))
self.checker.stop()
self.connection = None
self.connect()
示例5: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, host, queue):
self.queue = queue
self.host = host
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
self.callbacks = {}
def connect(self):
if self.connecting:
return
self.connecting = True
self.connection = TornadoConnection(
pika.ConnectionParameters(host=self.host),
on_open_callback=self.on_connected
)
self.connection.add_on_close_callback(self.on_closed)
def on_connected(self, connection):
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, chanel):
self.channel = chanel
self.channel.queue_declare(
queue=self.queue,
durable=True,
)
def on_basic_cancel(self, frame):
self.connection.close()
def on_closed(self, connection):
tornado.ioloop.IOLoop.instance().stop()
def send(self, body):
self.channel.basic_publish(
exchange='',
routing_key=self.queue,
body=json.dumps(body),
)
示例6: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self):
self.connected = False
self.connection = None
self.channel = None
self.messages = list()
def connect(self):
self.connection = TornadoConnection(on_open_callback=self.on_connected)
def on_connected(self, connection):
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
pika.log.info("channel open")
self.channel = channel
示例7: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, io_loop):
pika.log.info("PikaClient: __init__")
self.io_loop = io_loop
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
self.event_listeners = set([])
self.queue_name = "tornado-test-%i" % os.getpid()
def connect(self):
if self.connecting:
pika.log.info("PikaClient: Already connecting to RabbitMQ")
return
pika.log.info("PikaClient: Connecting to RabbitMQ")
self.connecting = True
# cred = pika.PlainCredentials('guest', 'guest')
param = pika.ConnectionParameters(
host="115.146.94.68",
# port=5672,
# virtual_host='/',
# credentials=cred
)
self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
self.connection.add_on_close_callback(self.on_closed)
def on_connected(self, connection):
pika.log.info("PikaClient: connected to RabbitMQ")
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
pika.log.info("PikaClient: Channel open, Declaring exchange")
self.channel = channel
self.channel.exchange_declare(exchange="www", type="direct", callback=self.on_exchange_declared)
return
def on_exchange_declared(self, frame):
pika.log.info("PikaClient: Exchange Declared, Declaring Queue")
self.channel.queue_declare(
queue=self.queue_name, auto_delete=True, durable=False, exclusive=False, callback=self.on_queue_declared
)
return
def on_queue_declared(self, frame):
pika.log.info("PikaClient: Queue Declared, Binding Queue")
self.channel.queue_bind(
exchange="www", queue=self.queue_name, routing_key="client", callback=self.on_queue_bound
)
def on_queue_bound(self, frame):
pika.log.info("PikaClient: Queue Bound, Issuing Basic Consume")
self.channel.basic_consume(consumer_callback=self.on_message, queue=self.queue_name, no_ack=True)
def on_closed(self, connection):
pika.log.info("PikaClient: rabbit connection closed")
self.io_loop.stop()
def on_message(self, channel, method, header, body):
pika.log.info("PikaClient: message received: %s" % body)
self.notify_listeners(body)
def send_message(self, body):
self.channel.basic_publish(exchange="www", routing_key="server", body=body)
def notify_listeners(self, body):
for listener in self.event_listeners:
listener.write_message(body)
pika.log.info("PikaClient: notified %s" % repr(listener))
def add_event_listener(self, listener):
self.event_listeners.add(listener)
pika.log.info("PikaClient: listener %s added" % repr(listener))
def remove_event_listener(self, listener):
try:
self.event_listeners.remove(listener)
pika.log.info("PikaClient: listener %s removed" % repr(listener))
except KeyError:
pass
示例8: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, io_loop):
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
self.ioloop = io_loop
def connect(self):
if self.connecting:
logger.info('PikaClient: Already connecting to RabbitMQ')
return
logger.info('PikaClient: Connecting to RabbitMQ on port 5672, Object: %s', self)
self.connecting = True
credentials = pika.PlainCredentials(RABBIT_USERNAME, RABBIT_PASS)
param = pika.ConnectionParameters(host=RABBIT_URL,
port=5672,
virtual_host=RABBIT_VHOST,
credentials=credentials)
self.connection = TornadoConnection(param,
on_open_callback=self.on_connected)
logger.info("Connection to rabbit")
global pika_connected
pika_connected = True
def on_connected(self, connection):
logger.info('PikaClient: Connected to RabbitMQ on :5672')
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
logger.info('PikaClient: Channel Open, Declaring Exchange, Channel ID: %s', channel)
self.channel = channel
logger.info("setting channel")
logger.info(channel)
self.channel.exchange_declare(exchange='tornado',
type="direct",
durable=False,
auto_delete=True)
def declare_queue(self, token):
logger.info('PikaClient: Exchange Declared, Declaring Queue')
self.queue_name = token
self.channel.queue_declare(queue=self.queue_name,
durable=False,
auto_delete=True,
callback=self.on_queue_declared)
def on_queue_declared(self, frame):
self.channel.queue_bind(exchange='tornado',
queue=self.queue_name,
routing_key=self.queue_name,
callback=self.on_queue_bound)
def on_queue_bound(self, frame):
logger.info('PikaClient: Queue Bound, Issuing Basic Consume')
self.channel.basic_consume(consumer_callback=self.on_pika_message,
queue=self.queue_name,
no_ack=True)
def on_pika_message(self, channel, method, header, body):
logger.info('PikaCient: Message receive, delivery tag #%i', method.delivery_tag)
message = json.loads(body)
# TODO: decrement unread count
for i in websockets[message['token']]:
try:
if 'action' in message and message["action"] == "kick" and 'token_to_kick' in message:
if i.authentication_token == message["token_to_kick"]:
REDIS_CONNECTION.srem('%s-%s' % ('members', message['token']), message["token_to_kick"])
i.close()
continue
del message["token_to_kick"]
del message["action"]
body = json.dumps(message)
i.write_message(body)
except Exception as error:
logger.exception("exception while writing message to client: {}".format(error.message))
def on_basic_cancel(self, frame):
logger.info('PikaClient: Basic Cancel Ok')
# If we don't have any more consumer processes running close
self.connection.close()
def on_closed(self, connection):
# We've closed our pika connection so stop the demo
self.ioloop.IOLoop.instance().stop()
def sample_message(self, ws_msg):
logger.info(ws_msg)
logger.info("zaa")
token = json.loads(ws_msg)['token']
properties = pika.BasicProperties(
content_type="text/plain", delivery_mode=1)
logger.info(self.channel)
#.........这里部分代码省略.........
示例9: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self):
# Construct a queue name we'll use for this instance only
#Giving unique queue for each consumer under a channel.
self.queue_name = "/4EAqhJ1FaJuuGc07qS3KwZZamZypZDMVfpx/TIO/CaqNjhuV7+36tEUCIdzborOFqtcxSBvgjW0Ywe+s0Sj9Q6+t+TfRk44kxZpw8Eyg8H6LcKbiUzWmZqMIfdsTUfqRWLaAj2UN2ZVHf6hmDyyOEbEGTl6t0qUXXNJDMaSlBLVAqsDAQAB"#"queue-%s" % (id(self),)
# Default values
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
#Webscoket object.
self.websocket = None
def connect(self):
if self.connecting:
pika.log.info('PikaClient: Already connecting to RabbitMQ')
return
pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672, Object: %s' % (self,))
self.connecting = True
credentials = pika.PlainCredentials('guest', 'guest')
param = pika.ConnectionParameters(host='pepperjack.stanford.edu',
port=5672,
virtual_host="/",
credentials=credentials)
self.connection = TornadoConnection(param,
on_open_callback=self.on_connected)
#Currently this will close tornado ioloop.
#self.connection.add_on_close_callback(self.on_closed)
def on_connected(self, connection):
pika.log.info('PikaClient: Connected to RabbitMQ on localhost:5672')
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
pika.log.info('PikaClient: Channel Open, Declaring Exchange, Channel ID: %s' % (channel,))
self.channel = channel
self.channel.exchange_declare(exchange='tornado',
type="direct",
auto_delete=True,
durable=False,
callback=self.on_exchange_declared)
def on_exchange_declared(self, frame):
pika.log.info('PikaClient: Exchange Declared, Declaring Queue')
pika.log.info(self.queue_name)
self.channel.queue_declare(auto_delete=False,
queue = self.queue_name,
durable=True,
exclusive=False,
callback=self.on_queue_declared)
def on_queue_declared(self, frame):
pika.log.info('PikaClient: Queue Declared, Binding Queue')
self.channel.queue_bind(exchange='tornado',
queue=self.queue_name,
routing_key='tornado.*',
callback=self.on_queue_bound)
def on_queue_bound(self, frame):
pika.log.info('PikaClient: Queue Bound, Issuing Basic Consume')
self.channel.basic_consume(consumer_callback=self.on_pika_message,
queue=self.queue_name,
no_ack=True)
def on_pika_message(self, channel, method, header, body):
pika.log.info('PikaCient: Message receive, delivery tag #%i' % \
method.delivery_tag)
#Send the Cosumed message via Websocket to browser.
self.websocket.write_message(base64.encodestring(body))
def on_basic_cancel(self, frame):
pika.log.info('PikaClient: Basic Cancel Ok')
# If we don't have any more consumer processes running close
self.connection.close()
def on_closed(self, connection):
# We've closed our pika connection so stop the demo
tornado.ioloop.IOLoop.instance().stop()
def sample_message(self, ws_msg):
#.........这里部分代码省略.........
示例10: NotiPikator
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class NotiPikator(object):
'''
This is a singleton-wannabe class for connecting, listening and
triggering events from RabbitMQ.
It uses the <pika> library with adapter to internal Tornado ioloop
for non-blocking operations on MQ.
'''
def __init__(self, *args, **kwargs):
self._listeners = {} # username: {conn_ts: callback, conn_ts2: callback2}
self._host = kwargs.get('host', 'localhost')
self._port = kwargs.get('port', 5672)
def add_listener(self, rkey, conn_ts, callback):
'Add listener callback for a specific routing key'
rkey_listeners = self._listeners.get(rkey, {})
rkey_listeners[conn_ts] = callback
self._listeners[rkey] = rkey_listeners
self.channel.queue_bind(exchange='mail',
routing_key=str(rkey),
queue='mailq')
logger.debug('new listener for <%s, %s> was set' % (rkey, conn_ts))
def remove_listener(self, rkey, conn_ts):
'Remove callback for a routing key'
try:
rkey_listeners = self._listeners[rkey]
if conn_ts in rkey_listeners:
del rkey_listeners[conn_ts]
logger.debug('listener for <%s, %s> was removed' % (rkey, conn_ts))
if len(rkey_listeners) == 0:
del self._listeners[rkey]
self.channel.queue_unbind(exchange='mail',
routing_key=str(rkey),
queue='mailq')
logger.debug('not listening for <%s> events anymore' % (rkey, ))
except KeyError:
pass # disconnected another time?
def connect(self):
'Establish RabbitMQ connection.'
self.connection = TornadoConnection(
pika.ConnectionParameters(host=self._host, port=self._port),
on_open_callback=self.on_connected)
logger.info('connecting to RabbitMQ...')
def on_connected(self, connection):
'Callback for successfully established connecction'
logger.info('connection with RabbitMQ is established')
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
'Callback for successfully opened connection channel'
logger.debug('RabbitMQ channel is opened')
self.channel = channel
self.channel.exchange_declare(exchange='mail', type='direct')
self.channel.queue_declare(queue='mailq',
callback=self.on_queue_declared,
arguments={'x-message-ttl':30000})
def on_queue_declared(self, frame):
'Callback for successfull exchange hub and a queue on it declaration'
logger.debug('queue_declared event fired')
self.channel.basic_consume(self.on_message, queue='mailq', no_ack=True)
def on_message(self, ch, method, properties, body):
'Callback on incoming event for some binded routing_key'
logger.debug('message received: %s %s' % (method.routing_key, body,))
rkey_listeners = self._listeners.get(method.routing_key, {})
for ts, cb in rkey_listeners.items():
cb(body)
示例11: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, io_loop):
pika.log.info('PikaClient: __init__')
self.io_loop = io_loop
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
self.event_listeners = set([])
def connect(self):
if self.connecting:
pika.log.info('PikaClient: Already connecting to RabbitMQ')
return
pika.log.info('PikaClient: Connecting to RabbitMQ')
self.connecting = True
cred = pika.PlainCredentials('guest', 'guest')
param = pika.ConnectionParameters(
host='localhost',
port=5672,
virtual_host='/',
credentials=cred
)
self.connection = TornadoConnection(param,
on_open_callback=self.on_connected)
self.connection.add_on_close_callback(self.on_closed)
def on_connected(self, connection):
pika.log.info('PikaClient: connected to RabbitMQ')
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
pika.log.info('PikaClient: Channel open, Declaring exchange')
self.channel = channel
# declare exchanges, which in turn, declare
# queues, and bind exchange to queues
def on_closed(self, connection):
pika.log.info('PikaClient: rabbit connection closed')
self.io_loop.stop()
def on_message(self, channel, method, header, body):
pika.log.info('PikaClient: message received: %s' % body)
self.notify_listeners(event_factory(body))
def notify_listeners(self, event_obj):
# here we assume the message the sourcing app
# post to the message queue is in JSON format
event_json = json.dumps(event_obj)
for listener in self.event_listeners:
listener.write_message(event_json)
pika.log.info('PikaClient: notified %s' % repr(listener))
def add_event_listener(self, listener):
self.event_listeners.add(listener)
pika.log.info('PikaClient: listener %s added' % repr(listener))
def remove_event_listener(self, listener):
try:
self.event_listeners.remove(listener)
pika.log.info('PikaClient: listener %s removed' % repr(listener))
except KeyError:
pass
示例12: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, io_loop, ank_accessor, host_address):
#pika.log.info('PikaClient: __init__')
self.io_loop = io_loop
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
self.event_listeners = set([])
self.queue_name = 'webserver-%i' % os.getpid()
self.ank_accessor = ank_accessor
self.host_address = host_address
def connect(self):
if self.connecting:
#pika.log.info('PikaClient: Already connecting to RabbitMQ')
return
#pika.log.info('PikaClient: Connecting to RabbitMQ')
self.connecting = True
#cred = pika.PlainCredentials('guest', 'guest')
param = pika.ConnectionParameters(
host= self.host_address,
#port=5672,
#virtual_host='/',
#credentials=cred
)
try:
self.connection = TornadoConnection(param,
on_open_callback=self.on_connected)
self.connection.add_on_close_callback(self.on_closed)
except pika.exceptions.AMQPConnectionError:
print("Unable to connect to RabbitMQ")
def on_connected(self, connection):
#pika.log.info('PikaClient: connected to RabbitMQ')
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
#pika.log.info('PikaClient: Channel open, Declaring exchange')
self.channel = channel
self.channel.exchange_declare(exchange='www',
type="direct",
callback=self.on_exchange_declared)
return
def on_exchange_declared(self, frame):
#pika.log.info('PikaClient: Exchange Declared, Declaring Queue')
self.channel.queue_declare(queue=self.queue_name,
auto_delete=True,
durable=False,
exclusive=False,
callback=self.on_queue_declared)
return
def on_queue_declared(self, frame):
#pika.log.info('PikaClient: Queue Declared, Binding Queue')
self.channel.queue_bind(exchange='www',
queue=self.queue_name,
routing_key='client',
callback=self.on_queue_bound)
def on_queue_bound(self, frame):
#pika.log.info('PikaClient: Queue Bound, Issuing Basic Consume')
self.channel.basic_consume(consumer_callback=self.on_message,
queue=self.queue_name,
no_ack=True)
def on_closed(self, connection):
#pika.log.info('PikaClient: rabbit connection closed')
self.io_loop.stop()
def on_message(self, channel, method, header, body):
#pika.log.info('PikaClient: message received: %s' % body)
import zlib
try:
body = zlib.decompress(body)
except zlib.error:
pass # likely not compressed body
body_parsed = json.loads(body)
if body_parsed.has_key("anm"):
print "Received updated network topology"
try:
self.ank_accessor.anm = body_parsed['anm']
#TODO: could process diff and only update client if data has changed -> more efficient client side
self.update_listeners("overlays")
# TODO: find better way to replace object not just local reference, as need to replace for RequestHandler too
except Exception, e:
print "Exception is", e
elif body_parsed.has_key("ip_allocations"):
alloc = json.loads(body_parsed['ip_allocations'])
self.ank_accessor.ip_allocation = alloc
self.update_listeners("ip_allocations")
示例13: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
def __init__(self, io_loop):
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
self.ioloop = io_loop
def connect(self):
if self.connecting:
logger.info('PikaClient: Already connecting to RabbitMQ')
return
logger.info('PikaClient: Connecting to RabbitMQ on port 5672, Object: %s', self)
self.connecting = True
credentials = pika.PlainCredentials(RABBIT_USERNAME, RABBIT_PASS)
param = pika.ConnectionParameters(host=RABBIT_URL,
port=5672,
virtual_host='/',
credentials=credentials)
self.connection = TornadoConnection(param,
on_open_callback=self.on_connected)
global pika_connected
pika_connected = True
def on_connected(self, connection):
logger.info('PikaClient: Connected to RabbitMQ on :5672')
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
logger.info('PikaClient: Channel Open, Declaring Exchange, Channel ID: %s', channel)
self.channel = channel
self.channel.exchange_declare(exchange='tornado',
type='direct',
durable=False,
auto_delete=True)
def declare_queue(self, token):
logger.info('PikaClient: Exchange Declared, Declaring Queue')
self.queue_name = token
self.channel.queue_declare(queue=self.queue_name,
durable=False,
auto_delete=True,
callback=self.on_queue_declared)
def on_queue_declared(self, frame):
self.channel.queue_bind(exchange='tornado',
queue=self.queue_name,
routing_key=self.queue_name,
callback=self.on_queue_bound)
def on_queue_bound(self, frame):
logger.info('PikaClient: Queue Bound, Issuing Basic Consume')
self.channel.basic_consume(consumer_callback=self.on_pika_message,
queue=self.queue_name,
no_ack=True)
def on_pika_message(self, channel, method, header, body):
logger.info('PikaCient: Message receive, delivery tag #%i', method.delivery_tag)
message = json.loads(body)
for i in websockets[message['token']]:
try:
i.write_message(body)
except:
logger.exception('exception while writing message to client')
def on_basic_cancel(self, frame):
logger.info('PikaClient: Basic Cancel Ok')
# If we don't have any more consumer processes running close
self.connection.close()
def on_closed(self, connection):
# We've closed our pika connection so stop the demo
self.ioloop.IOLoop.instance().stop()
def sample_message(self, ws_msg):
token = json.loads(ws_msg)['token']
properties = pika.BasicProperties(
content_type='text/plain', delivery_mode=1)
self.channel.basic_publish(exchange='tornado',
routing_key=token,
body=ws_msg,
properties=properties)
示例14: AQMPMultiCastAsyncRxQueueManager
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class AQMPMultiCastAsyncRxQueueManager(RxMultiDelegateQueueWrapper):
def __init__(self, io_loop, exchange):
super().__init__()
self.logger = logging.getLogger(__name__)
self.logger.info('AQMPMultiCastAsyncRxQueueManager: __init__')
self.io_loop = io_loop
self.exchange = exchange
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
def start(self, routing_key):
if self.connecting:
self.logger.info('AQMPMultiCastAsyncRxQueueManager: Already connecting to RabbitMQ')
return
self.routing_key = routing_key
self.logger.info('AQMPMultiCastAsyncRxQueueManager: Connecting to RabbitMQ')
self.connecting = True
cred = pika.PlainCredentials('guest', 'guest')
param = pika.ConnectionParameters(
host='localhost',
port=5672,
virtual_host='/',
credentials=cred
)
self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
self.connection.add_on_close_callback(self.on_closed)
self.io_loop.start()
# Callback 1
def on_connected(self, connection):
self.logger.info('AQMPMultiCastAsyncRxQueueManager: connected to RabbitMQ')
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
# Callback 2
def on_channel_open(self, channel):
self.logger.info('AQMPMultiCastAsyncRxQueueManager: Channel open, Declaring exchange')
self.channel = channel
self.channel.queue_declare(exclusive=True, callback=self.on_queue_declared)
# Callback 3
def on_queue_declared(self, frame):
"""Called when RabbitMQ has told us our Queue has been declared, frame is the response from RabbitMQ"""
self.queue_name = frame.method.queue
self.channel.queue_bind(self.on_queue_bind, exchange=self.exchange, queue=self.queue_name, routing_key=self.routing_key)
# Callback 4
def on_queue_bind(self, frame):
self.channel.basic_consume(self.on_message, queue=self.queue_name, no_ack=True)
def on_closed(self, connection):
self.logger.info('AQMPMultiCastAsyncRxQueueManager: rabbit connection closed')
self.io_loop.stop()
def on_message(self, channel, method, header, body):
self.logger.info('AQMPMultiCastAsyncRxQueueManager: message received: %s' % body)
self.notify_delegates(body)
示例15: PikaClient
# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import channel [as 别名]
class PikaClient(object):
tornado_callback = None
_closing = False
_connect_index = 0
_connect_pull = None
_one_respond_made = None
_waiting_to_reconnect = 3
_expire_reconnect = 15
_last_reconnect_fail = None
def __init__(self, logger,
queue_answer, queue_read, queue_create,
node_list):
# Construct a queue name we'll use for this instance only
self.queue_answer = queue_answer
# Create queue for sending
self.queue_read = queue_read
self.queue_create = queue_create
self.logger = logger
self.connected = False
self.connecting = False
self.connection = None
self.channel = None
# A place for us to keep messages sent to us by Rabbitmq
self.messages = list()
# A place for us to put pending messages while we're waiting to connect
self.pending = list()
self._connect_pull = []
for node in node_list:
self._connect_pull.append(
pika.ConnectionParameters(
host=node[0], port=int(node[1])))
def connect(self):
if self.connecting:
self.logger.warning('Already connecting to RabbitMQ')
return
param = self._connect_pull[self._connect_index]
self.logger.debug('Connecting to RabbitMQ on '
'{host}:{port}'.format(host=param.host,
port=param.port))
self.connecting = True
# TODO: add on_connection_error
try:
self.connection = TornadoConnection(
param,
on_open_callback=self.on_connected
)
self.connection.add_on_close_callback(self.on_closed)
except AMQPConnectionError:
self.reconnect()
def on_connected(self, connection):
self.logger.debug('Connected to RabbitMQ on: '
'{connection}'.format(connection=connection))
self.connected = True
self.connection = connection
self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel):
self.logger.debug('Channel Open, Declaring Exchange')
self.channel = channel
self.channel.exchange_declare(exchange='tornado',
type='topic',
durable=True,
callback=self.on_exchange_declared)
def on_exchange_declared(self, frame):
self.logger.debug('Exchange Declared, Declaring Queue')
self.channel.queue_declare(queue=self.queue_answer,
durable=True,
callback=self.on_queue_declared)
self.channel.queue_declare(queue=self.queue_create,
durable=True,
callback=lambda frame:
self.channel.queue_bind(
exchange='tornado',
queue=self.queue_create,
routing_key=self.queue_create,
callback=None))
self.channel.queue_declare(queue=self.queue_read,
durable=True,
callback=lambda frame:
self.channel.queue_bind(
exchange='tornado',
queue=self.queue_read,
routing_key=self.queue_read,
callback=None))
def on_queue_declared(self, frame):
self.logger.debug('Queue Declared, Binding Queue')
self.channel.queue_bind(exchange='tornado',
queue=self.queue_answer,
callback=self.on_queue_bound)
def on_queue_bound(self, frame):
#.........这里部分代码省略.........