我在使用者中使用pika.BlockingConnection
,它为每条消息执行一些任务。我还添加了信号处理,以便消费者在完全执行所有任务后正常死亡。
在处理消息和接收信号时,我只是从函数中获得"signal received"
,但代码并没有退出。所以,我决定检查在回调函数结束时接收到的信号。问题是,我要检查信号多少次,因为这段代码中会有更多的函数。有没有更好的方法来处理信号而不过度?
import signal
import sys
import pika
from time import sleep
received_signal = False
all_over = False
def signal_handler(signal, frame):
global received_signal
print "signal received"
received_signal = True
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
mq_connection = pika.BlockingConnection(pika.ConnectionParameters(my_mq_server, virtual_host='test'))
mq_channel = mq_connection.channel()
def callback(ch, method, properties, body):
if received_signal:
print "Exiting, as a kill signal is already received"
exit(0)
print body
sleep(50)
mq_channel.basic_ack(delivery_tag=method.delivery_tag)
print "Message consumption complete"
if received_signal:
print "Exiting, as a kill signal is already received"
exit(0)
try:
print ' [*] Waiting for messages. To exit press CTRL+C'
mq_channel.basic_consume(callback, queue='test')
mq_channel.start_consuming()
except Exception:
mq_channel.close()
exit()
这是我在这里的第一个问题,如果需要更多的细节,请告诉我。
我认为这正是您想要的:
#!/usr/bin/python
import signal
import sys
import pika
from contextlib import contextmanager
received_signal = False
processing_callback = False
def signal_handler(signal, frame):
global received_signal
print "signal received"
received_signal = True
if not processing_callback:
sys.exit()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
@contextmanager
def block_signals():
global processing_callback
processing_callback = True
try:
yield
finally:
processing_callback = False
if received_signal:
sys.exit()
def callback(ch, method, properties, body):
with block_signals:
print body
sum(xrange(0, 200050000)) # sleep gets interrupted by signals, this doesn't.
mq_channel.basic_ack(delivery_tag=method.delivery_tag)
print "Message consumption complete"
if __name__ == "__main__":
try:
mq_connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
mq_channel = mq_connection.channel()
print ' [*] Waiting for messages. To exit press CTRL+C'
mq_channel.basic_consume(callback, queue='test')
mq_channel.start_consuming()
except Exception as e:
mq_channel.close()
sys.exit()
我使用了一个contextmanager来处理阻塞信号,这样所有的逻辑都隐藏在回调本身之外。这也应该使代码的重用更加容易。只是为了澄清它是如何工作的,它相当于:
def callback(ch, method, properties, body):
global processing_callback
processing_callback = True
try:
print body
sum(xrange(0, 200050000))
mq_channel.basic_ack(delivery_tag=method.delivery_tag)
print "Message consumption complete"
finally:
processing_callback = False
if received_signal:
sys.exit()