def run(self): settings.logger.info("RUN") # Connect to rabbitmq server self.connection = pika.AsyncoreConnection( pika.ConnectionParameters(settings.host, settings.port, settings.virtual_host ) ) settings.logger.debug("Build a connection to rabbitmq by %s, %s, %s" % (settings.host, settings.port, settings.virtual_host)) self.channel = self.connection.channel() settings.logger.debug("get a channel") # Create exchange if not exist self.channel.exchange_declare(exchange = settings.exchange_name, type = settings.routing_type, durable = settings.durable) settings.logger.debug("Exchange %s declared", settings.exchange_name) # Create queue if not exist self.channel.queue_declare( queue = settings.queue_name, durable = settings.durable, auto_delete = settings.auto_delete ) settings.logger.debug("Queue %s declared." % settings.queue_name) # Binding exchange and queue with routing key self.channel.queue_bind(exchange = settings.exchange_name, queue = settings.queue_name, routing_key = settings.routing_key) settings.logger.debug("Binding queue %s to exchagge %s with routing key %s" % (settings.queue_name, settings.exchange_name, settings.routing_key)) self.channel.basic_qos(prefetch_count = settings.prefetch_count) self.channel.basic_consume(self.callback, queue = settings.queue_name, no_ack = settings.no_ack) pika.asyncore_loop()
def loop(self): def callback(ch, method, header, body): message = json.loads(body) player = message['player'] cardsRemaining = message['cardsRemaining'] if player=="player1": self.player1 = [player, cardsRemaining] elif player=="player2": self.player2 = [player, cardsRemaining] if len(self.player1) > 0 and len(self.player2) > 0: print 'Player 1 cards: ' print self.player1[1] print 'Player 2 cards: ' print self.player2[1] if self.player1[1] > self.player2[1]: print self.player1[0] +" wins!" elif self.player1[1] < self.player2[1]: print self.player2[0] +" wins!" else: print "Both win!" del self.player1[:] del self.player2[:] self.startNewGame() self.channel.basic_consume(callback, queue =self.queue_name, no_ack=True) pika.asyncore_loop()
def receive_message(self): self.logger.debug("Connecting to RabbitMQ broker...") self.conn = pika.AsyncoreConnection(pika.ConnectionParameters( '127.0.0.1', credentials = pika.PlainCredentials('guest', 'guest'), heartbeat = 10)) self.logger.debug('Connected to %r' % (self.conn.server_properties,)) self.logger.debug("Creating channel...") ch = self.conn.channel() self.logger.debug("Declaring queue...") ch.queue_declare(queue="twitter", durable=True, exclusive=False, auto_delete=False) def handle_delivery(ch, method, header, body): self.logger.debug("Received a message. Parsing...") self.logger.debug("method=%r" % method) self.logger.debug("header=%r" % header) self.logger.debug(" body=%r" % body) ch.basic_ack(delivery_tag = method.delivery_tag) self.logger.debug("self.message_store = %s" % self.message_store) self.message_store.append(pickle.loads(body)) self.logger.debug("Consuming a message...") ch.basic_consume(handle_delivery, queue = "twitter") self.logger.debug("Looping...") pika.asyncore_loop() self.conn.close() self.logger.debug('Close reason: %s' % str(conn.connection_close))
def loop(self): def callback(ch, method, header, body): if body=="newRound": if self.cardsRemaining() > 0: card1 = self.removeCard() card2 = self.removeCard() message = {"card1": {"suit":card1[0], "value": card1[1]}, "card2": {"suit":card2[0], "value": card2[1]}} self.channel.basic_publish(exchange =self.exchange_name, routing_key='cards', body =json.dumps(message)) else: message = "emptyDeck" self.channel.basic_publish(exchange =self.exchange_name, routing_key='players', body =message) elif method.routing_key=="deckNbr": message = json.loads(body) deckNbr = message['deckNbr'] self.startNewGame(deckNbr) self.channel.basic_consume(callback, queue =self.queue_name, no_ack=True) pika.asyncore_loop()
def loop(self): def callback(ch, method, header, body): if method.routing_key == "cards": message = json.loads(body) self.playRound(message) elif method.routing_key == "deckNbr": del self.deckL[:] self.channel.basic_consume(callback, queue=self.queue_name, no_ack=True) pika.asyncore_loop()
def run(self): # Open RabbitMQ connection connection = AsyncoreConnection(ConnectionParameters(host=self.host, credentials=self.credentials)) channel = connection.channel() # Declare the queue channel.queue_declare(queue=self.queue, durable=True) # Subscribe to the queue channel.basic_consume(self._capture_screenshot, queue=self.queue, no_ack=True) # Wait for data asyncore_loop()
def test_publish_after_consume(self): conn_a = pika.AsyncoreConnection(pika.ConnectionParameters('127.0.0.1')) ch_a = conn_a.channel() ch_a.queue_declare(queue="test", durable=True, \ exclusive=False, auto_delete=False) def handle_delivery(_channel, method, header, body): ch_a.basic_ack(delivery_tag = method.delivery_tag) conn_a.close() tag = ch_a.basic_consume(handle_delivery, queue='test') ch_a.basic_publish(exchange='', routing_key="test", body="Hello World!",) pika.asyncore_loop()
def call(self, n): corr_id = str(uuid.uuid4()) self.requests[corr_id] = None self.channel.basic_publish(exchange='', routing_key='rpc_queue', properties=pika.BasicProperties( reply_to = self.callback_queue, correlation_id = corr_id, ), body=str(n)) while self.requests[corr_id] is None: pika.asyncore_loop(count=1) response = self.requests[corr_id] del self.requests[corr_id] return int(response)
def call(self, n): corr_id = str(uuid.uuid4()) self.requests[corr_id] = None self.channel.basic_publish(exchange='', routing_key='rpc_queue', properties=pika.BasicProperties( reply_to=self.callback_queue, correlation_id=corr_id, ), body=str(n)) while self.requests[corr_id] is None: pika.asyncore_loop(count=1) response = self.requests[corr_id] del self.requests[corr_id] return int(response)
def run(self): """ Poll the queue at a certain interval for new messages. """ try: while True: self.log('Loop start', level=logging.DEBUG) connection = None channel = None try: connection = self.fresh_connection() if connection.connection_open: self.log('Got connection', level=logging.DEBUG) channel = connection.channel() channel.queue_declare( queue=self.__queueName, durable=True, exclusive=False, auto_delete=False) channel.basic_consume( consumer=self.__handle_delivery, queue=self.__queueName) pika.asyncore_loop() self.log('Finished with connection', level=logging.DEBUG) else: self.log('No connection', level=logging.DEBUG) finally: if not channel is None: self.log('Closing channel', level=logging.DEBUG) channel.close() channel = None if not connection is None: self.log('Closing connection', level=logging.DEBUG) connection.close() connection = None time.sleep(self.__loopTimeout) except QuitApplication as e: self.log('Quitting application ({0})'.format(e.signalName)) finally: self.log('Log Server stopped')
def _setup_tubes(self): """ creates the in 'config' configured input and output """ chan = self.channel ret = [] print self.config[self.NAME]["amqp"]["exchanges"] for k, v in self.config[self.NAME]["amqp"]["exchanges"].items(): o = C() inp = v["in"] if "in" in v else None out = v["out"] if "out" in v else None o.name = k print str(k), str(inp), str(out) if inp and inp["exchange"]: log.info("generating Input Queue" + str(inp)) inp["type"] = inp["type"] if "type" in inp else "fanout" chan.exchange_declare(**inp) o.qname = chan.queue_declare(exclusive=True).queue o.inp = inp["exchange"] chan.queue_bind(exchange=inp["exchange"], queue=o.qname) o.consume = lambda cb, queue: chan.basic_consume(cb, queue=queue, no_ack=True) o.start_loop = lambda: pika.asyncore_loop() if out and out["exchange"]: out["type"] = out["type"] if "type" in out else "fanout" log.info("generating Output Exchange" + str(out)) chan.exchange_declare(**out) o.out = out["exchange"] o.publish = lambda msg, exchange: self.channel.basic_publish( exchange=exchange, routing_key="", body=msg ) ret.append(o) print ret return ret
def monitor(self, qname, callback): conn = pika.AsyncoreConnection(pika.ConnectionParameters( '127.0.0.1', credentials=pika.PlainCredentials('guest', 'guest'))) ch = conn.channel() if not self.queue_exists: ch.queue_declare(queue=qname, durable=False, exclusive=False, auto_delete=False) ch.queue_bind(queue=qname, exchange=self.exchange_name) print "Binding queue %s to exchange %s" % (qname, self.exchange_name) #ch.queue_bind(queue=qname, exchange=self.exchange_name, routing_key=qname) self.queue_exists = True ch.basic_consume(callback, queue=qname) pika.asyncore_loop() print 'Close reason:', conn.connection_close
def run_rabbit_interface(self): connection = pika.AsyncoreConnection(pika.ConnectionParameters( 'localhost', credentials = pika.PlainCredentials('guest', 'guest') )) channel = connection.channel() channel.exchange_declare( exchange = 'octo-maker.process-heartbeat', type = 'fanout' ) result = channel.queue_declare(exclusive=True) queue_name = result.queue print "[octo-dad] listening as queue '%s'" % queue_name channel.queue_bind( exchange = 'octo-maker.process-heartbeat', queue = queue_name ) result = channel.queue_declare(exclusive=True) control_queue_name = result.queue channel.queue_bind( exchange = 'octo-maker.control', queue = control_queue_name, routing_key = 'octo-maker.node.*' ) channel.basic_consume( self.handle_process_heartbeat, queue = queue_name ) channel.basic_consume( self.handle_control_message, queue = control_queue_name ) pika.asyncore_loop()
def run(self): settings.logger.info("RUN") # Connect to rabbitmq server self.connection = pika.AsyncoreConnection( pika.ConnectionParameters(settings.host, settings.port, settings.virtual_host)) settings.logger.debug( "Build a connection to rabbitmq by %s, %s, %s" % (settings.host, settings.port, settings.virtual_host)) self.channel = self.connection.channel() settings.logger.debug("get a channel") # Create exchange if not exist self.channel.exchange_declare(exchange=settings.exchange_name, type=settings.routing_type, durable=settings.durable) settings.logger.debug("Exchange %s declared", settings.exchange_name) # Create queue if not exist self.channel.queue_declare(queue=settings.queue_name, durable=settings.durable, auto_delete=settings.auto_delete) settings.logger.debug("Queue %s declared." % settings.queue_name) # Binding exchange and queue with routing key self.channel.queue_bind(exchange=settings.exchange_name, queue=settings.queue_name, routing_key=settings.routing_key) settings.logger.debug( "Binding queue %s to exchagge %s with routing key %s" % (settings.queue_name, settings.exchange_name, settings.routing_key)) self.channel.basic_qos(prefetch_count=settings.prefetch_count) self.channel.basic_consume(self.callback, queue=settings.queue_name, no_ack=settings.no_ack) pika.asyncore_loop()
def loop(self): def callback(ch, method, header, body): if body=="emptyDeck": message = {"player": self.name, "cardsRemaining": self.cardsRemaining()} self.channel.basic_publish(exchange =self.exchange_name, routing_key='game', body =json.dumps(message)) elif method.routing_key=="pileCards": message = json.loads(body) if message['name']==self.name: self.addCard(message) elif method.routing_key=="deckNbr": del self.deckL[:] print 'del player' print len(self.deckL) self.channel.basic_consume(callback, queue =self.queue_name, no_ack=True) pika.asyncore_loop()
def _setup_tubes(self): """ creates the in 'config' configured input and output """ chan = self.channel inp = self.config[self.MODULE_NAME]['amqp']['in'] out = self.config[self.MODULE_NAME]['amqp']['out'] if inp['exchange']: log.info('generating Input Queue'+ str(inp)) chan.exchange_declare(**inp) self.qname = chan.queue_declare(exclusive=True).queue chan.queue_bind(exchange=inp['exchange'],queue=self.qname) self.consume = lambda cb : chan.basic_consume(cb,queue=self.qname,no_ack=True) self.start_loop = lambda : pika.asyncore_loop() if out['exchange']: log.info('generating Output Exchange'+ str(out)) chan.exchange_declare(**out) self.publish = lambda msg: self.channel.basic_publish(exchange=out['exchange'],routing_key='',body=msg)
conn = pika.AsyncoreConnection(pika.ConnectionParameters( (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1', credentials = pika.PlainCredentials('guest', 'guest'))) print 'Connected to %r' % (conn.server_properties,) qname = (len(sys.argv) > 2) and sys.argv[2] or 'test' ch = conn.channel() ch.queue_declare(queue=qname, durable=True, exclusive=False, auto_delete=False) should_quit = False def handle_delivery(ch, method, header, body): print "method=%r" % (method,) print "header=%r" % (header,) print " body=%r" % (body,) ch.basic_ack(delivery_tag = method.delivery_tag) global should_quit should_quit = True tag = ch.basic_consume(handle_delivery, queue = qname) while conn.is_alive() and not should_quit: pika.asyncore_loop(count = 1) if conn.is_alive(): ch.basic_cancel(tag) conn.close() print conn.connection_close
#!/usr/bin/env python # see rabbitmqsend.py for setup import pika connection = pika.AsyncoreConnection(pika.ConnectionParameters(host="localhost")) channel = connection.channel() channel.queue_declare(queue="hello") def callback(ch, method, properties, body): print " [x] Received %r" % (body,) channel.basic_consume(callback, queue="hello", no_ack=True) print "[*] Waiting for messages. To exit press Ctrl+C" pika.asyncore_loop()
def start(connections, count=100, timeout=1): socket_map = {} for conn in connections: socket_map[conn.dispatcher._fileno] = conn.dispatcher pika.asyncore_loop(socket_map, count=count, timeout=timeout)
def doLoop(self): print "entering loop" pika.asyncore_loop()
if (len(sys.argv) == 2): builder_id = sys.argv[1] def callback(ch, method, properties, body): print " [x] Received %r" % (body, ) msg_obj = {} msg_obj['builder_id'] = builder_id msg_obj['body'] = "Build starting..." msg_obj['first_message'] = True json_str = json.dumps(msg_obj) channel.basic_publish( exchange='from_worker_exchange', routing_key="loquat", # key.frombuilders body=json_str) time.sleep(1) msg_obj = {} msg_obj['builder_id'] = builder_id msg_obj['body'] = '\na second message' msg_obj['first_message'] = False json_str = json.dumps(msg_obj) channel.basic_publish( exchange='from_worker_exchange', routing_key="loquat", # key.frombuilders body=json_str) channel.basic_consume(callback, queue=from_web_queue.queue, no_ack=True) pika.asyncore_loop()