pika 使用的坑

最近使用pika的异步模式,一直报错,错误提示如下:

Traceback (most recent call last):
  File "mq_test1.py", line 36, in 
    connection.ioloop.start()
  File "/usr/local/lib/python3.6/site-packages/pika/adapters/select_connection.py", line 543, in start
    self._poller.start()
  File "/usr/local/lib/python3.6/site-packages/pika/adapters/select_connection.py", line 804, in start
    self._process_timeouts()
  File "/usr/local/lib/python3.6/site-packages/pika/adapters/select_connection.py", line 494, in process_timeouts
    self._timer.process_timeouts()
  File "/usr/local/lib/python3.6/site-packages/pika/adapters/select_connection.py", line 329, in process_timeouts
    timeout.callback()
  File "/usr/local/lib/python3.6/site-packages/pika/adapters/utils/connection_workflow.py", line 341, in _on_overall_timeout
    self._amqp_conn.close(320, msg)
  File "/usr/local/lib/python3.6/site-packages/pika/connection.py", line 1283, in close
    raise exceptions.ConnectionWrongStateError(msg)
pika.exceptions.ConnectionWrongStateError: Illegal close(320, "Timeout while setting up AMQP to '192.168.122.1'/(, , 6, '', ('192.168$
122.1', 5672)); ssl=False") request on > because it was called whil$
 connection state=CLOSED.

源码如下:

import pika


def on_open(connection):
   connection.channel(on_channel_open)


import time as timer
from time import time


def on_channel_open(channel):
   message = 'message body value' * 100
   start = time()
   for i in range(5):
       channel.basic_publish('test_exchange',
                           '',
                           message,
                           pika.BasicProperties(content_type='text/plain',
                                                delivery_mode=2))
       if  i % 1000 == 0:
           print('publish', i)
#         timer.sleep(10)
   end = time() - start
   print(end)

# Step #1: Connect to RabbitMQ
parameters = pika.URLParameters('amqp://test:[email protected]:5672/test')

connection = pika.SelectConnection(parameters=parameters,
                                  on_open_callback=on_open)

try:

   # Step #2 - Block on the IOLoop
   connection.ioloop.start()

# Catch a Keyboard Interrupt to make sure that the connection is closed cleanly
except KeyboardInterrupt:

   # Gracefully close the connection
   connection.close()

   # Start the IOLoop again so Pika can communicate, it will stop on its own when the connection is closed
   connection.ioloop.start()

这是因为pika的channel函数原型为如下形式
pika 使用的坑_第1张图片
on_open_callback 不再是位置参数,而是关键字参数,所以在调用是不能使用connection.channel(on_channel_open) 而是要改为connection.channel(on_open_callback=on_channel_open)

你可能感兴趣的:(python学习)