Skip to content

Instantly share code, notes, and snippets.

@ciknight
Last active December 13, 2016 08:45
Show Gist options
  • Save ciknight/4181e668fa9dff87b820c3d1a5b4f941 to your computer and use it in GitHub Desktop.
Save ciknight/4181e668fa9dff87b820c3d1a5b4f941 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import pika
import tornado.log
from tornado.log import gen_log
tornado.log.enable_pretty_logging(logger=gen_log)
class Pika(object):
amqp_url = "ampq://guest:[email protected]:5672/"
def __init__(self):
self._url = Pika.amqp_url
self._connection = None
self._closing = False
def on_connection_open(self, conn):
gen_log.info("connected")
gen_log.info('Adding connection close callback')
self._connection.add_on_close_callback(self.on_connection_closed)
def connect(self):
params = pika.URLParameters(self._url)
return pika.TornadoConnection(params, on_open_callback=self.on_connection_open)
def reconnect(self):
#self._connection.ioloop.stop()
if not self._closing:
gen_log.info("reconnect...")
self._connection = self.connect()
#self._connection.ioloop.start()
def on_connection_closed(self, connection, replay_code, replay_text):
if self._closing:
self._connection.ioloop.stop()
else:
gen_log.info("Connection closed, reopeninig in 5 sec")
self._connection.add_timeout(5, self.reconnect)
def run(self):
gen_log.info("running")
self._connection = self.connect()
self._connection.ioloop.start()
if __name__ == "__main__":
p = Pika()
conn = p.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment