Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.94 KB | None | 0 0
  1. import logging
  2. import pika
  3. import time
  4.  
  5. LOG_FORMAT = ('%(levelname) -1s %(asctime)s %(name) -1s %(funcName) '
  6. '-1s %(lineno) -5d: %(message)s')
  7. LOGGER = logging.getLogger(__name__)
  8.  
  9.  
  10. user="user"
  11. password="password"
  12. host="localhost"
  13. queue="test"
  14.  
  15.  
  16. class amqpConsumer(object):
  17.  
  18. def __init__(self):
  19. """Create a new instance of the consumer class, passing in the AMQP
  20. URL used to connect to RabbitMQ.
  21.  
  22. :param str amqp_url: The AMQP url to connect with
  23.  
  24. """
  25. self._connection = None
  26. self._channel = None
  27. self._closing = False
  28. self._consumer_tag = None
  29.  
  30. def connect(self):
  31. """This method connects to RabbitMQ, returning the connection handle.
  32. When the connection is established, the on_connection_open method
  33. will be invoked by pika.
  34.  
  35. :rtype: pika.SelectConnection
  36.  
  37. """
  38. LOGGER.info('Connecting to %s', host)
  39.  
  40. credentials=pika.PlainCredentials(user, password)
  41. return pika.SelectConnection(pika.ConnectionParameters(host=host,credentials=credentials,heartbeat_interval=0),
  42. self.on_connection_open,
  43. stop_ioloop_on_close=False)
  44.  
  45.  
  46. def on_connection_open(self, unused_connection):
  47. """This method is called by pika once the connection to RabbitMQ has
  48. been established. It passes the handle to the connection object in
  49. case we need it, but in this case, we'll just mark it unused.
  50.  
  51. :type unused_connection: pika.SelectConnection
  52.  
  53. """
  54. LOGGER.info('Connection opened')
  55. self.add_on_connection_close_callback()
  56. self.open_channel()
  57.  
  58. def add_on_connection_close_callback(self):
  59. """This method adds an on close callback that will be invoked by pika
  60. when RabbitMQ closes the connection to the publisher unexpectedly.
  61.  
  62. """
  63. LOGGER.info('Adding connection close callback')
  64. self._connection.add_on_close_callback(self.on_connection_closed)
  65.  
  66. def on_connection_closed(self, connection, reply_code, reply_text):
  67. """This method is invoked by pika when the connection to RabbitMQ is
  68. closed unexpectedly. Since it is unexpected, we will reconnect to
  69. RabbitMQ if it disconnects.
  70.  
  71. :param pika.connection.Connection connection: The closed connection obj
  72. :param int reply_code: The server provided reply_code if given
  73. :param str reply_text: The server provided reply_text if given
  74.  
  75. """
  76. self._channel = None
  77. if self._closing:
  78. self._connection.ioloop.stop()
  79. else:
  80. LOGGER.warning('Connection closed, reopening in 5 seconds: (%s) %s',
  81. reply_code, reply_text)
  82. self._connection.add_timeout(5, self.reconnect)
  83.  
  84. def reconnect(self):
  85. """Will be invoked by the IOLoop timer if the connection is
  86. closed. See the on_connection_closed method.
  87.  
  88. """
  89. # This is the old connection IOLoop instance, stop its ioloop
  90. self._connection.ioloop.stop()
  91.  
  92. if not self._closing:
  93.  
  94. # Create a new connection
  95. self._connection = self.connect()
  96.  
  97. # There is now a new connection, needs a new ioloop to run
  98. self._connection.ioloop.start()
  99.  
  100. def open_channel(self):
  101. """Open a new channel with RabbitMQ by issuing the Channel.Open RPC
  102. command. When RabbitMQ responds that the channel is open, the
  103. on_channel_open callback will be invoked by pika.
  104.  
  105. """
  106. LOGGER.info('Creating a new channel')
  107. self._connection.channel(on_open_callback=self.on_channel_open)
  108.  
  109. def on_channel_open(self, channel):
  110. """This method is invoked by pika when the channel has been opened.
  111. The channel object is passed in so we can make use of it.
  112.  
  113. Since the channel is now open, we'll declare the exchange to use.
  114.  
  115. :param pika.channel.Channel channel: The channel object
  116.  
  117. """
  118. LOGGER.info('Channel opened')
  119. self._channel = channel
  120. self.add_on_channel_close_callback()
  121.  
  122. self.start_consuming()
  123.  
  124.  
  125. def add_on_channel_close_callback(self):
  126. """This method tells pika to call the on_channel_closed method if
  127. RabbitMQ unexpectedly closes the channel.
  128.  
  129. """
  130. LOGGER.info('Adding channel close callback')
  131. self._channel.add_on_close_callback(self.on_channel_closed)
  132.  
  133. def on_channel_closed(self, channel, reply_code, reply_text):
  134. """Invoked by pika when RabbitMQ unexpectedly closes the channel.
  135. Channels are usually closed if you attempt to do something that
  136. violates the protocol, such as re-declare an exchange or queue with
  137. different parameters. In this case, we'll close the connection
  138. to shutdown the object.
  139.  
  140. :param pika.channel.Channel: The closed channel
  141. :param int reply_code: The numeric reason the channel was closed
  142. :param str reply_text: The text reason the channel was closed
  143.  
  144. """
  145. LOGGER.warning('Channel %i was closed: (%s) %s',
  146. channel, reply_code, reply_text)
  147. self._connection.close()
  148.  
  149.  
  150. def start_consuming(self):
  151. """This method sets up the consumer by first calling
  152. add_on_cancel_callback so that the object is notified if RabbitMQ
  153. cancels the consumer. It then issues the Basic.Consume RPC command
  154. which returns the consumer tag that is used to uniquely identify the
  155. consumer with RabbitMQ. We keep the value to use it when we want to
  156. cancel consuming. The on_message method is passed in as a callback pika
  157. will invoke when a message is fully received.
  158.  
  159. """
  160. LOGGER.info('Issuing consumer related RPC commands')
  161. self.add_on_cancel_callback()
  162. self._channel.basic_qos(prefetch_count=1)
  163. self._consumer_tag = self._channel.basic_consume(self.on_message,queue)
  164.  
  165. def add_on_cancel_callback(self):
  166. """Add a callback that will be invoked if RabbitMQ cancels the consumer
  167. for some reason. If RabbitMQ does cancel the consumer,
  168. on_consumer_cancelled will be invoked by pika.
  169.  
  170. """
  171. LOGGER.info('Adding consumer cancellation callback')
  172. self._channel.add_on_cancel_callback(self.on_consumer_cancelled)
  173.  
  174. def on_consumer_cancelled(self, method_frame):
  175. """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
  176. receiving messages.
  177.  
  178. :param pika.frame.Method method_frame: The Basic.Cancel frame
  179.  
  180. """
  181. LOGGER.info('Consumer was cancelled remotely, shutting down: %r',
  182. method_frame)
  183. if self._channel:
  184. self._channel.close()
  185.  
  186. def on_message(self, unused_channel, basic_deliver, properties, body):
  187. """Invoked by pika when a message is delivered from RabbitMQ. The
  188. channel is passed for your convenience. The basic_deliver object that
  189. is passed in carries the exchange, routing key, delivery tag and
  190. a redelivered flag for the message. The properties passed in is an
  191. instance of BasicProperties with the message properties and the body
  192. is the message that was sent.
  193.  
  194. :param pika.channel.Channel unused_channel: The channel object
  195. :param pika.Spec.Basic.Deliver: basic_deliver method
  196. :param pika.Spec.BasicProperties: properties
  197. :param str|unicode body: The message body
  198.  
  199. """
  200. LOGGER.info('Received message # %s from %s',
  201. basic_deliver.delivery_tag, properties.app_id)
  202.  
  203. time.sleep(10*60)
  204.  
  205. self.acknowledge_message(basic_deliver.delivery_tag)
  206.  
  207.  
  208. def not_acknowledge_message(self, delivery_tag):
  209. """Not Acknowledge the message delivery from RabbitMQ by sending a
  210. Basic.Nack RPC method for the delivery tag.
  211.  
  212. :param int delivery_tag: The delivery tag from the Basic.Deliver frame
  213.  
  214. """
  215. LOGGER.info('Not acknowledging message %s', delivery_tag)
  216. self._channel.basic_nack(delivery_tag)
  217.  
  218.  
  219. def acknowledge_message(self, delivery_tag):
  220. """Acknowledge the message delivery from RabbitMQ by sending a
  221. Basic.Ack RPC method for the delivery tag.
  222.  
  223. :param int delivery_tag: The delivery tag from the Basic.Deliver frame
  224.  
  225. """
  226. LOGGER.info('Acknowledging message %s', delivery_tag)
  227. self._channel.basic_ack(delivery_tag)
  228.  
  229. def stop_consuming(self):
  230. """Tell RabbitMQ that you would like to stop consuming by sending the
  231. Basic.Cancel RPC command.
  232.  
  233. """
  234. if self._channel:
  235. LOGGER.info('Sending a Basic.Cancel RPC command to RabbitMQ')
  236. self._channel.basic_cancel(self.on_cancelok, self._consumer_tag,nowait=False)
  237.  
  238. def on_cancelok(self, unused_frame):
  239. """This method is invoked by pika when RabbitMQ acknowledges the
  240. cancellation of a consumer. At this point we will close the channel.
  241. This will invoke the on_channel_closed method once the channel has been
  242. closed, which will in-turn close the connection.
  243.  
  244. :param pika.frame.Method unused_frame: The Basic.CancelOk frame
  245.  
  246. """
  247. LOGGER.info('RabbitMQ acknowledged the cancellation of the consumer')
  248. self.close_channel()
  249.  
  250. def close_channel(self):
  251. """Call to close the channel with RabbitMQ cleanly by issuing the
  252. Channel.Close RPC command.
  253.  
  254. """
  255. LOGGER.info('Closing the channel')
  256. self._channel.close()
  257.  
  258. def run(self):
  259. """Run the example consumer by connecting to RabbitMQ and then
  260. starting the IOLoop to block and allow the SelectConnection to operate.
  261.  
  262. """
  263. self._connection = self.connect()
  264. self._connection.ioloop.start()
  265.  
  266. def stop(self):
  267. """Cleanly shutdown the connection to RabbitMQ by stopping the consumer
  268. with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok
  269. will be invoked by pika, which will then closing the channel and
  270. connection. The IOLoop is started again because this method is invoked
  271. when CTRL-C is pressed raising a KeyboardInterrupt exception. This
  272. exception stops the IOLoop which needs to be running for pika to
  273. communicate with RabbitMQ. All of the commands issued prior to starting
  274. the IOLoop will be buffered but not processed.
  275.  
  276. """
  277. LOGGER.info('Stopping')
  278. self._closing = True
  279. self.stop_consuming()
  280. self.close_connection()
  281. #self._connection.ioloop.start()
  282. LOGGER.info('Stopped')
  283.  
  284. def close_connection(self):
  285. """This method closes the connection to RabbitMQ."""
  286. LOGGER.info('Closing connection')
  287. self._connection.close()
  288.  
  289.  
  290. def main():
  291.  
  292. print ' [*] Waiting for messages. To exit press CTRL+C'
  293.  
  294. logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
  295.  
  296. consumer = amqpConsumer()
  297. try:
  298. consumer.run()
  299. except KeyboardInterrupt:
  300. consumer.stop()
  301.  
  302.  
  303. if __name__ == '__main__':
  304.  
  305. main() # (this code was run as script)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement