2012-03-26 3 views
12

스레드를 허용 할 수없는 다른 응용 프로그램에서 RabbitMQ 대기열에서주고받는 Python 코드를 실행 중입니다. 이것은 매우 새내기의 질문이지만, 메시지가 있는지 확인한 후 듣기를 끊는 것이 없으면 그냥 확인해 볼 수 있습니까? 그런 작업에 대한 기본 "Hello world"예제를 어떻게 변경해야합니까? 현재 메시지를 받으면 소비를 멈추지 만, 메시지가 없다면 기다리는 것이 계속됩니다. 메시지가 없으면 강제로 기다리지 않는 방법은 무엇입니까? 또는 주어진 시간 동안 만 기다릴 수 있습니까?RabbitMQ가 있으면 메시지 하나만 남기고

import pika 

global answer 

def send(msg): 
    connection = pika.BlockingConnection(pika.ConnectionParameters()) 
    channel = connection.channel() 
    channel.queue_declare(queue='toJ') 
    channel.basic_publish(exchange='', routing_key='toJ', body=msg) 
    connection.close() 

def receive(): 
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) 
    channel = connection.channel() 
    channel.queue_declare(queue='toM') 
    channel.basic_consume(callback, queue='toM', no_ack=True) 
    global answer 
    return answer 

def callback(ch, method, properties, body): 
    ch.stop_consuming() 
    global answer 
    answer = body 
+0

루비 API는 큐의 길이를 확인하는 방법 .. 당신은 파이썬 문서를 확인하신 후이있다? –

답변

15

좋아, 나는 다음과 같은 해결책을 발견 :

def receive(): 
    parameters = pika.ConnectionParameters(RabbitMQ_server) 
    connection = pika.BlockingConnection(parameters) 
    channel = connection.channel() 
    channel.queue_declare(queue='toM') 
    method_frame, header_frame, body = channel.basic_get(queue = 'toM')   
    if method_frame.NAME == 'Basic.GetEmpty': 
     connection.close() 
     return '' 
    else:    
     channel.basic_ack(delivery_tag=method_frame.delivery_tag) 
     connection.close() 
     return body 
+0

method_frame이 None인지 확인하는 것도 중요합니다. 큐에 메시지가 더 이상 없으면 channel.basic_get (queue = 'toM')은 None-s와 함께 반환됩니다. – balas

관련 문제