当前位置: 首页>>代码示例>>Python>>正文


Python TornadoConnection.add_on_close_callback方法代码示例

本文整理汇总了Python中pika.adapters.tornado_connection.TornadoConnection.add_on_close_callback方法的典型用法代码示例。如果您正苦于以下问题:Python TornadoConnection.add_on_close_callback方法的具体用法?Python TornadoConnection.add_on_close_callback怎么用?Python TornadoConnection.add_on_close_callback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pika.adapters.tornado_connection.TornadoConnection的用法示例。


在下文中一共展示了TornadoConnection.add_on_close_callback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Sender

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class Sender(object):
    def __init__(self, settings, io_loop):
        self.io_loop = io_loop
        self.channel = None
        self.exchange = "poly"

        credentials = None
        if settings.get("username", None):
            credentials = pika.PlainCredentials(
                settings["username"],
                settings["password"]
            )
        self.connection_parameters = None
        if credentials or settings.get("host", None) or settings.get("vhost"):
            self.connection_parameters = pika.ConnectionParameters(
                credentials=credentials,
                host=settings.get("host", None),
                port=settings.get("port", None),
                virtual_host=settings.get("vhost", None)
            )
        else:
            raise Exception("NO self.connection_parameters")
        self.settings = settings

    def connect(self):
        logging.info("MQ connect...")
        try:
            self.connection = TornadoConnection(
                self.connection_parameters,
                self.on_connected
            )
            self.connection.add_on_close_callback(self.on_close)
        except socket.error, e:
            logging.warn("connection failed, trying again in 5 seconds")
            self.io_loop.add_timeout(time.time() + 5, self.connect)
开发者ID:philwhln,项目名称:poly,代码行数:37,代码来源:mq.py

示例2: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [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()
开发者ID:frutik,项目名称:test-rabbitmq-websocket-gw,代码行数:61,代码来源:pika_client.py

示例3: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [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
开发者ID:alex-moon,项目名称:plase,代码行数:54,代码来源:client.py

示例4: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class PikaClient(object):
    """A modified class as described in pika's demo_tornado.py.
    It handles the connection for the Tornado instance. Messaging/RPC
    callbacks are handled by the Tornado RequestHandler above."""

    def __init__(self):
        self.connecting = False
        self.connection = None
        self.channel = None
        # self.L = log_class.Logger()

    def connect(self):
        if self.connecting:
            log.info("Already connecting to RabbitMQ.")
            return
        # self.L.logger.info("Connecting to RabbitMQ")
        self.connecting = True
        creds = pika.PlainCredentials("guest", "guest")
        params = pika.ConnectionParameters(host="localhost", port=5672, virtual_host="/", credentials=creds)
        self.connection = TornadoConnection(params, on_open_callback=self.on_connect)
        self.connection.add_on_close_callback(self.on_closed)

    def on_connect(self, connection):
        self.connection = connection
        connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        # self.L.logger.info('Channel Open')
        self.channel = channel
        # I'm having trouble using named exchanges.
        ## channel.exchange_declare(exchange='rpc_ex', type='direct',
        ##                          auto_delete=True, durable=False,
        ##                          callback=self.on_exchange_declare)

    def on_exchange_declare(self, frame):
        log.info("Exchange declared.")

    def on_basic_cancel(self, frame):
        log.info("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()
开发者ID:nehald,项目名称:random_bits,代码行数:47,代码来源:front_end.py

示例5: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [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),
        )
开发者ID:MechanisM,项目名称:uglyrater,代码行数:47,代码来源:utils.py

示例6: Pika

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class Pika(object):

    """ rabbitMQ manager.  """

    def __init__(self):
        """ rabbitMQ manager init. """
        self.connection = None
        self.connecting = False
        self.channel = None

    def connect(self):
        """ rabbitMQ manager connect. """
        if self.connecting:
            logging.info('Already connecting to RabbitMQ')
            return
        logging.info('Connectiong to RabbitMQ')
        self.connecting = True
        credentials = pika.PlainCredentials('guest', 'guest')
        params = pika.ConnectionParameters(
            host='localhost',
            port=5672,
            virtual_host='/smsgo',
            credentials=credentials)
        self.connection = TornadoConnection(
            params, on_open_callback=self.on_connect)
        self.connection.add_on_close_callback(on_closed)

    def on_connect(self, connection):
        """ rabbitMQ manager on connect callback. """
        self.connection = connection
        connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        """ rabbitMQ manager on channel open callback. """
        logging.info('Channel Open')
        self.channel = channel

    #def on_exchange_declare(self, frame):
        #logging.info('Exchange Declare')

    def on_basic_cancel(self, frame):
        """ rabbitMQ manager on basic cancel callback. """
        logging.info('Basic Cancel Ok')
        self.connection.close()
开发者ID:Rick1125,项目名称:smsapi,代码行数:46,代码来源:tornado_pika.py

示例7: RabbitClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class RabbitClient(object):

    """Managing incoming messages from Rabbit Service"""

    def __init__(self, app=None):
        self.app = app
        self._connect()

    def _connect(self):
        conn = pika.ConnectionParameters(
            host=CREDS['host'], port=int(CREDS['port']),
            virtual_host='/',
            credentials=pika.PlainCredentials(
                CREDS['user'], CREDS['pasw']))

        self.tc = TornadoConnection(
            conn, on_open_callback=self.on_connected,
            on_open_error_callback=self.on_disconnect
        )

        self.tc.add_on_close_callback(self.on_disconnect)

    def on_disconnect(self, *args):
        logger.warning("Connection lost, reconnect in 5 seconds...")
        IOLoop.instance().add_timeout(
            time.time() + 5, self._connect)

    def on_connected(self, con):
        con.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        channel.basic_consume(consumer_callback=self.on_message,
                              queue=CREDS['queue'],
                              no_ack=True)

    def on_message(self, channel, method, header, body):
        self.app.manager.send(body)
开发者ID:rmuslimov,项目名称:fasttrace,代码行数:39,代码来源:trace.py

示例8: RabbitClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class RabbitClient(object):

  EXCHANGE = 'message'
  EXCHANGE_TYPE = 'topic'
  PUBLISH_INTERVAL = .001
  QUEUE = 'text'
  ROUTING_KEY = 'example.text'

  def __init__(self, app, ioloop):
    """Setup the example publisher object, passing in the URL we will use
    to connect to RabbitMQ.

    :param str amqp_url: The URL for connecting to RabbitMQ

    """
    self._connection = None
    self._channel = None
    self._deliveries = []
    self._acked = 0
    self._nacked = 0
    self._message_number = 0
    self._stopping = False
    self.app = app
    self.ioloop = ioloop

  ## Connection Logic ##########################################################

  def connect(self):
    LOGGER.info('Connecting to RabbitMQ')
    # exc_type, exc_value, exc_traceback = sys.exc_info()
    # traceback.print_tb(exc_traceback, limit=None, file=sys.stdout)
    # self.connecting = True

    self._connection = TornadoConnection(rc.connParam,
      on_open_callback=self.on_connection_open)

  def close_connection(self):
    """This method closes the connection to RabbitMQ."""
    LOGGER.info('Closing connection')
    self._connection.close()

  def add_on_connection_close_callback(self):
    LOGGER.info('Adding connection close callback')
    self._connection.add_on_close_callback(self.on_connection_closed)

  def on_connection_closed(self, method_frame):
    # if we loose the connection, try to reconnect
    LOGGER.warning('Server closed connection, reopening: (%s) %s',
             method_frame.method.reply_code,
             method_frame.method.reply_text)
    self._channel = None
    self._connection = self.connect()

  def on_connection_open(self, unused_connection):
    LOGGER.info('Connection opened')
    self.add_on_connection_close_callback()
    self.open_channel()

  def add_on_channel_close_callback(self):
    LOGGER.info('Adding channel close callback')
    self._channel.add_on_close_callback(self.on_channel_closed)

  def on_channel_closed(self, method_frame):
    # if rabbit closes the channel, quit server
    LOGGER.warning('Channel was closed: (%s) %s',
             method_frame.method.reply_code,
             method_frame.method.reply_text)
    self._connection.close()

  def on_channel_open(self, channel):
    LOGGER.info('Channel opened')
    self._channel = channel
    self.add_on_channel_close_callback()
    self.setupExngsQueues()

  def sendNodeCtrlMsg(self, nodeHostname, ctrlCode):
    self._channel.basic_publish(
      rc.msgExngAttr["exchange"],
      "node.{0}.cmd".format(nodeHostname),
      str(ctrlCode)
    )

  ## Message Route Init ########################################################

  def setupExngsQueues(self):
    LOGGER.info('')
    self.exngQueCount = 0
    self.exngQueNum = len(rc.svrExngs) + len(rc.svrQueues)
    # open all exchanges and queues we need asynchronously
    for exng in rc.svrExngs:
      self.setupExchange(exng)
    for queue in rc.svrQueues:
      self.setupQueue(queue)
    # callback fn counts when everything is declared
  def setupExchange(self, exng):
    LOGGER.info('Declaring exchange %s', exng["exchange"])
    self._channel.exchange_declare(self.onExngQueDeclare, **exng)
  def setupQueue(self, queue):
    LOGGER.info('Declaring queue %s', queue["queue"])
    self._channel.queue_declare(self.onExngQueDeclare, **queue)
#.........这里部分代码省略.........
开发者ID:bwasserm,项目名称:wifiwatt,代码行数:103,代码来源:wifiWattSrv.py

示例9: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [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
开发者ID:itsafire,项目名称:vdebootstrap,代码行数:74,代码来源:app.py

示例10: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [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")
开发者ID:ptokponnon,项目名称:autonetkit,代码行数:101,代码来源:webserver.py

示例11: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class PikaClient(object):

    def __init__(self, io_loop):
        logger.info('Initializing')
        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:
            logger.info('Already connecting to RabbitMQ')
            return

        logger.info('Connecting to RabbitMQ')
        self.connecting = True

        cred = pika.PlainCredentials(
            settings.BAGOU.get('AMQP_BROKER_USER'),
            settings.BAGOU.get('AMQP_BROKER_PASS'))
        param = pika.ConnectionParameters(
            host=settings.BAGOU.get('AMQP_BROKER_ADDR'),
            port=settings.BAGOU.get('AMQP_BROKER_PORT'),
            virtual_host=settings.BAGOU.get('AMQP_BROKER_PATH'),
            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):
        logger.info('Connected to RabbitMQ')
        self.connected = True
        self.connection = connection
        self.connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        logger.info('Channel open, Declaring exchange')
        self.channel = channel
        self.channel.queue_declare(
            queue=settings.BAGOU.get('QUEUE_NAME'),
            durable=True,
            exclusive=False,
            auto_delete=True,
            callback=self.on_queue_declared)

    def on_queue_declared(self, frame):
        self.channel.basic_consume(self.on_message, queue=settings.BAGOU.get('QUEUE_NAME'))

    def on_closed(self, connection):
        logger.info('RabbitMQ connection closed')
        self.io_loop.stop()

    def on_message(self, channel, method, header, body):
        logger.debug('Message received: %s' % body)
        self.notify_listeners(body)

    def notify_listeners(self, event_obj):
        event_json = json.loads(event_obj)
        channels = event_json.get('channel')

        for channel in channels:
            for listener in self.event_listeners:
                if channel:
                    if channel in listener.channels:
                        listener.write_message(event_obj)
                        logger.info('Notified %s (channels: %s)' % (repr(listener), listener.channels))
                else:
                    listener.write_message(event_obj)
                    logger.info('Notified %s' % repr(listener))

    def add_event_listener(self, listener):
        self.event_listeners.add(listener)
        logger.info('Listener %s added' % repr(listener))

    def remove_event_listener(self, listener):
        try:
            self.event_listeners.remove(listener)
            logger.info('Listener %s removed' % repr(listener))
        except KeyError:
            pass
开发者ID:farzeni,项目名称:django-bagou,代码行数:86,代码来源:client.py

示例12: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class PikaClient(object):

    def __init__(self, config, app=None):
        self.classifier = Classifier()
        # Connection params
        self.host = config['host'] or 'localhost'
        self.port = config['port'] or '5672'
        self.vhost = config['vhost'] or '/'
        self.user = config['user'] or 'guest'
        self.passwd = config['passwd'] or 'guest'
        self.exchange = config['exchange'] or 'twitter2'
        self.queue_name = config['queue_name'] or 'twitter_topic_feed'
        self.routing_key = config['routing_key'] or 'twitter_topic_feed'

        # Default values
        self.connected = False
        self.connecting = False
        self.connection = None
        self.channel = None

        self.app = app
        self.event_listeners = set([])
        # 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()

    def connect(self):
        if self.connecting:
            print('PikaClient: Already connecting to RabbitMQ')
            return
        print('PikaClient: Connecting to RabbitMQ on %s:%i' \
            % (self.host, self.port))
        self.connecting = True

        credentials = pika.PlainCredentials(self.user, self.passwd)

        param = pika.ConnectionParameters(host=self.host, port=self.port,
            virtual_host=self.vhost, credentials=credentials)

        logging.debug('Events: Connecting to AMQP Broker: %s:%i' % (self.host,
            self.port))

        # from pika.adapters import SelectConnection
        # connection = SelectConnection(parameters, on_connected)
        self.connection = TornadoConnection(param,
            on_open_callback=self.on_connected)

        self.connection.add_on_close_callback(self.on_closed)

    def on_connected(self, connection):
        print('PikaClient: Connected to RabbitMQ on %s:%i' \
            % (self.host, self.port))

        self.connected = True
        self.connection = connection
        self.connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        print('PikaClient: Channel Open, Declaring Exchange %s' \
            % self.exchange)

        self.channel = channel
        self.channel.exchange_declare(exchange=self.exchange,
                                      type="direct",
                                      durable=False,
                                      callback=self.on_exchange_declared)

    def on_exchange_declared(self, frame):
        print('PikaClient: Exchange Declared, Declaring Queue %s' \
            % self.queue_name)
        self.channel.queue_declare(queue=self.queue_name,
                                   durable=False,
                                   exclusive=False,
                                   callback=self.on_queue_declared)

    def on_queue_declared(self, frame):
        print('PikaClient: Queue Declared, Binding Queue')
        self.channel.queue_bind(exchange=self.exchange,
                                queue=self.queue_name,
                                routing_key=self.routing_key,
                                callback=self.on_queue_bound)

    def on_queue_bound(self, frame):
        print('PikaClient: Queue Bound, Issuing Basic Consume')
        self.channel.basic_consume(consumer_callback=self.on_message,
                                   queue=self.queue_name,
                                   no_ack=True)
        # Send any messages pending
        for properties, body in self.pending:
            self.channel.basic_publish(exchange=self.exchange,
                                       routing_key=self.routing_key,
                                       body=body,
                                       properties=properties)

    def on_basic_cancel(self, frame):
        print('PikaClient: Basic Cancel Ok')
#.........这里部分代码省略.........
开发者ID:frankfarrell,项目名称:ireland-sentiment,代码行数:103,代码来源:client.py

示例13: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [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
开发者ID:coana,项目名称:ank_v3_dev,代码行数:89,代码来源:rabbit_websocket.py

示例14: LoginPublish

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [as 别名]
class LoginPublish(object):

    def __init__(self):
        self.channel = None
        self.connection = None
        self.messages = []

    def initialcon(self):
        _logger.debug("pikapublish begin initialcon")
        credentials = pika.PlainCredentials('mxpub', 'mhearts2015')
        parameters =  pika.ConnectionParameters('localhost', 6500, credentials=credentials)
        self.connection = TornadoConnection(parameters, on_open_callback = self.on_connected)

    def on_connected(self, connection):
        _logger.debug("pikapublish begin on_connected")
        self.connection = connection
        self.connection.channel(self.on_channel_open)
        self.connection.add_on_close_callback(self.on_connection_closed)

    def on_connection_closed(self, connection, reply_code, reply_text):
        _logger.info("connection closed")
        self.connection.add_timeout(5, self.initialcon)

    def on_channel_open(self, channel):
        _logger.debug("pikapublish begin on_channel_open")
        self.channel = channel
        self.publishmsg()
        
    def releasecon(self):
        if self.connection:
            self.connection.close()

    def pushmsg(self, loginkey, body):
        _logger.debug("begin pushmsg %r  %s" % (body, loginkey))
        if not loginkey or not body:
            return

        self.messages.append({"key":loginkey, "body":body})
        self.publishmsg()

    def publishmsg(self):
        _logger.debug("begin to publishmsg")
        if not self.channel:
            _logger.debug("begin to open channel")
            self.initialcon()
            return

        for item in self.messages:
            key = item.get("key", "")
            body = item.get("body", "")

            _logger.info("begin to publish %s body = %r" % (key, body))
            if not isinstance(key, str) and not isinstance(key, bytes):
                _logger.error("invalid key")
                continue

            noti_body = json.dumps(body)
            try:
                self.channel.basic_publish(exchange = 'pclogin',
                                           routing_key = key,
                                           body = noti_body)
            except Exception as e:
                _logger.error("pikapublish  catch exception {0}".format(e))


        self.messages[:] = []
开发者ID:micjerry,项目名称:deploy,代码行数:68,代码来源:loginpublish.py

示例15: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import add_on_close_callback [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='115.146.93.175',
            #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.queue_declare(queue='hello')
        self.channel.basic_consume(self.on_message,
                      queue='hello',
                      no_ack=True)
        # 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(body)

    def send_message(self, body):
        self.channel.basic_publish(exchange='',
                      routing_key='hello',
                      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):
        print "added 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
开发者ID:sk2,项目名称:ANK-NG,代码行数:77,代码来源:rabbit_websocket.py


注:本文中的pika.adapters.tornado_connection.TornadoConnection.add_on_close_callback方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。