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


Python TornadoConnection.close方法代码示例

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


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

示例1: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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

示例2: AMQPClient

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

    channels = {}

    def __init__(self, uri, logger, on_connected_callback=None):
        self._uri = uri or 'amqp://guest:[email protected]:5672/%2f'
        self._logger = logger or logging.getLogger(self.__class__.__name__)
        self._on_connected_callback = on_connected_callback
        self._amqp_connect()

    @property
    def uri(self):
        return self._uri

    @property
    def connection(self):
        return self._connection

    def __getattr__(self, name):
        if name in self.channels.keys():
            return self.channels[name]
        self.channels[name] = AMQPChannelClient(self, name)
        return self.channels[name]

    def __getitem__(self, name):
        return self.__getattr__(name)

    def _amqp_connect(self):
        self._connection = TornadoConnection(pika.URLParameters(self.uri),
            on_open_callback=self._on_amqp_opened, stop_ioloop_on_close=True)

    def _on_amqp_opened(self, connection):
        self._logger.debug('AMQP connection opened')
        self.connection.add_on_close_callback(self._on_connection_closed)
        if self._on_connected_callback:
            self._on_connected_callback()

    def _on_connection_closed(self, connection):
        #TODO: Log disconnection details...
        #self.log.warning('Server closed connection, reopening: (%s) %s',
                         #method_frame.method.reply_code,
                         #method_frame.method.reply_text)
        #self.log.debug(connection._is_method_frame())
        self._connection = self._amqp_connect()

    def close(self):
        for channel in self.channels.values():
            channel.cancel_consume()
        self._logger.debug('Closing AMQP connection')
        self._connection.close()
开发者ID:puentesarrin,项目名称:physalis,代码行数:52,代码来源:amqp_client.py

示例3: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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

示例4: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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

示例5: Pika

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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

示例6: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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):
#.........这里部分代码省略.........
开发者ID:NODCode,项目名称:nodcode,代码行数:103,代码来源:PikaClient.py

示例7: PikaClient

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

    def __init__(self, chat_id):

        # Construct a queue name we'll use for this instance only

        # Giving unique queue for each consumer under a channel.
        self.queue_name = "queue-%s" % (id(self),)
        # Default values
        self.connected = False
        self.connecting = False
        self.connection = None
        self.channel = None
        self.chat_id = chat_id

        # Webscoket object.
        self.websocket = None

    def connect(self):

        if self.connecting:
                print('PikaClient: Already connecting to RabbitMQ')
                return

        print('PikaClient: Connecting to RabbitMQ on localhost:5672, Object: %s' % (self,))

        self.connecting = True

        credentials = pika.PlainCredentials('guest', 'guest')
        param = pika.ConnectionParameters(host='localhost',
                                          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):
        print('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):

        print('PikaClient: Channel Open, Declaring Exchange, Channel ID: %s' %
              (channel,))
        self.channel = channel

        self.channel.exchange_declare(exchange='chat',
                                      type="direct",
                                      callback=self.on_exchange_declared)

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

    def on_queue_declared(self, frame):

        print('PikaClient: Queue Declared, Binding Queue')
        self.channel.queue_bind(exchange='chat',
                                queue=self.queue_name,
                                routing_key=self.chat_id,
                                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_pika_message,
                                   queue=self.queue_name,
                                   no_ack=True)

    def on_pika_message(self, channel, method, header, body):
        print('PikaCient: Message receive, delivery tag #%i' %
              method.delivery_tag)

        # Send the Cosumed message via Websocket to browser.
        self.websocket.write_message(body.decode('utf8'))

    def on_basic_cancel(self, frame):
        print('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:sofian86,项目名称:sandbox,代码行数:92,代码来源:main.py

示例8: PikaClient

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

示例9: AsyncTransport

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [as 别名]
class AsyncTransport(BaseTransport):
    def _connect(self):
        self._connection = TornadoConnection(
            self._parameters,
            on_open_callback=self.on_connection_open,
            stop_ioloop_on_close=False
        )

    def on_connection_open(self, unused_connection):
        """This method is called by pika once the connection to RabbitMQ has
        been established. It passes the handle to the connection object in
        case we need it, but in this case, we'll just mark it unused.

        :type unused_connection: pika.SelectConnection

        """
        self._connection.add_on_close_callback(self.on_connection_closed)
        self._open_channel()

    def on_connection_closed(self, method_frame):
        self._connection = None
        self._connect()

    def close(self):
        self._connection.close()

    def _open_channel(self):
        """Open a new channel with RabbitMQ by issuing the Channel.Open RPC
        command. When RabbitMQ responds that the channel is open, the
        on_channel_open callback will be invoked by pika.

        """
        self._connection.channel(self._on_channel_open)

    def _on_channel_open(self, channel):
        self._channel = channel
        self._channel.basic_qos(prefetch_count=1)
        self.add_on_channel_close_callback()
        self.setup_exchange()

    def add_on_channel_close_callback(self):
        """This method tells pika to call the on_channel_closed method if
        RabbitMQ unexpectedly closes the channel.

        """
        self._channel.add_on_close_callback(self.on_channel_closed)

    def on_channel_closed(self, channel, reply_code, reply_text):
        """Invoked by pika when RabbitMQ unexpectedly closes the channel.
        Channels are usually closed if you attempt to do something that
        violates the protocol, such as re-declare an exchange or queue with
        different parameters. In this case, we'll close the connection
        to shutdown the object.

        :param pika.channel.Channel: The closed channel
        :param int reply_code: The numeric reason the channel was closed
        :param str reply_text: The text reason the channel was closed

        """
        LOGGER.warning('Channel %i was closed: (%s) %s',
                       channel, reply_code, reply_text)
        self._connection.close()

    def setup_exchange(self):
        """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
        command. When it is complete, the on_exchange_declareok method will
        be invoked by pika.

        :param str|unicode exchange_name: The name of the exchange to declare

        """
        self._channel.exchange_declare(self.on_exchange_declareok,
                                       self.EXCHANGE_NAME,
                                       self.EXCHANGE_TYPE)

    def on_exchange_declareok(self, unused_frame):
        """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
        command.

        :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame

        """
        LOGGER.info('Exchange declared')
        self.setup_queue(self.QUEUE)

    def setup_queue(self, queue_name):
        """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
        command. When it is complete, the on_queue_declareok method will
        be invoked by pika.

        :param str|unicode queue_name: The name of the queue to declare.

        """
        LOGGER.info('Declaring queue %s', queue_name)
        self._channel.queue_declare(self.on_queue_declareok, queue_name)

    def on_queue_declareok(self, method_frame):
        """Method invoked by pika when the Queue.Declare RPC call made in
        setup_queue has completed. In this method we will bind the queue
        and exchange together with the routing key by issuing the Queue.Bind
#.........这里部分代码省略.........
开发者ID:Bpless,项目名称:cronkite,代码行数:103,代码来源:transport.py

示例10: PikaClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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):
#.........这里部分代码省略.........
开发者ID:Mobisocial,项目名称:Musubi-iOS-OSS,代码行数:103,代码来源:server.py

示例11: RabbitClient

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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

示例12: ExamplePublisher

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [as 别名]
class ExamplePublisher(object):
  """This is an example publisher that will handle unexpected interactions
  with RabbitMQ such as channel and connection closures.

  If RabbitMQ closes the connection, it will reopen it. You should
  look at the output, as there are limited reasons why the connection may
  be closed, which usually are tied to permission related issues or
  socket timeouts.

  It uses delivery confirmations and illustrates one way to keep track of
  messages that have been sent and if they've been confirmed by RabbitMQ.

  """
  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

  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):
    """This method adds an on close callback that will be invoked by pika
    when RabbitMQ closes the connection to the publisher unexpectedly.

    """
    LOGGER.info('Adding connection close callback')
    self._connection.add_on_close_callback(self.on_connection_closed)

  def on_connection_closed(self, method_frame):
    """This method is invoked by pika when the connection to RabbitMQ is
    closed unexpectedly. Since it is unexpected, we will reconnect to
    RabbitMQ if it disconnects.

    :param pika.frame.Method method_frame: The method frame from RabbitMQ

    """
    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):
    """This method is called by pika once the connection to RabbitMQ has
    been established. It passes the handle to the connection object in
    case we need it, but in this case, we'll just mark it unused.

    :type unused_connection: pika.SelectConnection

    """
    LOGGER.info('Connection opened')
    self.add_on_connection_close_callback()
    self.open_channel()

  def add_on_channel_close_callback(self):
    """This method tells pika to call the on_channel_closed method if
    RabbitMQ unexpectedly closes the channel.

    """
    LOGGER.info('Adding channel close callback')
    self._channel.add_on_close_callback(self.on_channel_closed)

  def on_channel_closed(self, method_frame):
    """Invoked by pika when RabbitMQ unexpectedly closes the channel.
    Channels are usually closed if you attempt to do something that
    violates the protocol, such as redeclare an exchange or queue with
    different paramters. In this case, we'll close the connection
    to shutdown the object.

    :param pika.frame.Method method_frame: The Channel.Close method frame
#.........这里部分代码省略.........
开发者ID:bwasserm,项目名称:wifiwatt,代码行数:103,代码来源:fakeRaspi.py

示例13: LoginPublish

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [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

示例14: Dealer

# 需要导入模块: from pika.adapters.tornado_connection import TornadoConnection [as 别名]
# 或者: from pika.adapters.tornado_connection.TornadoConnection import close [as 别名]

#.........这里部分代码省略.........
		user			= User.find(_id=args['user_id'])
		print args['user_id']
		current_room	= self.room_list[args["room_id"]]
		(status, msg)	= current_room.sit(user, int(args["seat"]), source, private_key,stake)

		if status:
			message	= {"status": "success" }
		else:
			message = {"status": "failed", "msg": msg}
		self.channel.basic_publish( exchange    = self.exchange,
									routing_key = source,
									body        = json.dumps(message))

	def broadcast(self, routing_key, msg):
		self.channel.basic_publish(	exchange	= self.exchange,
									routing_key	= routing_key,
									body		= json.dumps(msg))

	def cmd_enter(self,args):
		routing_key = args['source']
		user_id = args['user_id']
		if args['room_id'] not in self.room_list:
			#self.cmd_create_room(args)
			message     = {'status':'failed'}
		else:
			current_room = self.room_list[args["room_id"]]

			message     = {'status':'success', "room":current_room.to_listener(user_id)}

		self.channel.basic_publish( exchange    = self.exchange,
				routing_key = routing_key,
				body        = json.dumps(message))
		#current_room.resend_last_next_message()


	def cmd_create_room(self, args):
		print "creating room"


		blind		= int(args["blind"])
		max_stake	= int(args["max_stake"])
		min_stake	= int(args["min_stake"])
		max_player	= int(args["max_player"])
		routing_key = args['source']
		roomType	= int(args["roomType"])


		newRoom = Room.new(self.exchange,blind,max_player,
				max_stake,
				min_stake,roomType)

		self.room_list[newRoom.id] = GameRoom(
				newRoom, args["user_id"], self,
				max_player,blind,min_stake,max_stake)
		print newRoom
		message = {"room_id":newRoom.id}

		self.channel.basic_publish( exchange    = self.exchange,
				routing_key = routing_key,
				body        = json.dumps(message))

		self.info.rooms += 1



	def on_message(self, channel, method, header, body):
		print "ON_MESSAGE!"
		obj = json.loads(body)
		print body
		method = getattr(self,"cmd_" + obj['method'])
		method(obj)

	def close(self):
		self.connection.close()


	def handle_init_file(self,fname,isDebug):
		info = Room.find_all(exchange = self.exchange)
		for room in info:
			room.remove()


	#	if os.path.isfile(fname):
		print len(fname)
		print os.getcwd()
		with open(fname) as f:
			for line in f:
				if line[0] == '#':
					continue

				(roomType,blind,max_stake,min_stake,max_player) = ( int(x) for x in line.strip().split(','))

				newRoom = Room.new(self.exchange,blind,max_player,
						max_stake,
						min_stake,roomType)
				self.room_list[newRoom.id] = GameRoom(
						newRoom, 1, self,
						max_player, blind, min_stake, max_stake)
				self.info.rooms += 1
				print newRoom
开发者ID:hackur,项目名称:HTML5-Texas-Hold-em-,代码行数:104,代码来源:dealer.py

示例15: PikaPublisher

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

    def __init__(self, amqp_parameters, exchange, exchange_type, queue, routing_key):
        self._exchange = exchange
        self._exchange_type = exchange_type
        self._queue = queue
        self._routing_key = routing_key

        self._connection = None
        self._channel = None
        self._deliveries = []
        self._acked = 0
        self._nacked = 0
        self._message_number = 0
        self._stopping = False
        self._params = amqp_parameters
        self._closing = False

        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

    def connect(self):
        self._connection = TornadoConnection(self._params, self.on_connection_open, stop_ioloop_on_close=False)

        LOGGER.info('Adding connection close callback')
        self._connection.add_on_close_callback(self.on_connection_closed)
        return self._connection

    def close_connection(self):
        LOGGER.info('Closing connection')
        self._closing = True
        self._connection.close()

    def on_connection_closed(self, connection, reply_code, reply_text):
        self._channel = None
        if self._closing:
            self._connection.ioloop.stop()
        else:
            LOGGER.warning('Connection closed, reopening in 5 seconds: (%s) %s',
                           reply_code, reply_text)
            self._connection.add_timeout(5, self.reconnect)

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

    def reconnect(self):
        # This is the old connection IOLoop instance, stop its ioloop
        self._connection.ioloop.stop()

        # Create a new connection
        self._connection = self.connect()

        # There is now a new connection, needs a new ioloop to run
        self._connection.ioloop.start()

    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, channel, reply_code, reply_text):
        LOGGER.warning('Channel was closed: (%s) %s', reply_code, reply_text)
        if not self._closing:
            self._connection.close()

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

    def setup_exchange(self, exchange_name):
        LOGGER.info('Declaring exchange %s', exchange_name)
        self._channel.exchange_declare(self.on_exchange_declareok,
                                       exchange_name,
                                       self._exchange_type, durable=True)

    def on_exchange_declareok(self, unused_frame):
        LOGGER.info('Exchange declared')
        self.setup_queue(self._queue)

    def setup_queue(self, queue_name):
        LOGGER.info('Declaring queue %s', queue_name)
        self._channel.queue_declare(self.on_queue_declareok, queue_name, durable = True)

    def on_queue_declareok(self, method_frame):
        LOGGER.info('Binding %s to %s with %s',
                    self._exchange, self._queue, self._routing_key)
        self._channel.queue_bind(self.on_bindok, self._queue,
                                 self._exchange, self._routing_key)

    def on_delivery_confirmation(self, method_frame):
        confirmation_type = method_frame.method.NAME.split('.')[1].lower()
        LOGGER.info('Received %s for delivery tag: %i',
                    confirmation_type,
                    method_frame.method.delivery_tag)
        if confirmation_type == 'ack':
            self._acked += 1
        elif confirmation_type == 'nack':
            self._nacked += 1
        self._deliveries.remove(method_frame.method.delivery_tag)
#.........这里部分代码省略.........
开发者ID:maheshgattani,项目名称:Tornado-RabbitMQ,代码行数:103,代码来源:pika_publisher.py


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