celery worker进程 传递消息

我在celery 里启动了多个work用来执行多个微信机器人,work进程一直轮询服务器消息。这种情况下 我需要给小机器人发送命令 。由此引出给clerery work进程发消息的问题。


class consumer():
    def __init__(self, routing_key, callback):
        EXCHANGE_NAME = "exchange_direct"

        credentials = pika.PlainCredentials('guest', 'guest')
        connection = pika.BlockingConnection(pika.ConnectionParameters(
            '127.0.0.1', 5672, '/', credentials))
        self.channel = connection.channel()
        pid = os.getpid()
        self.channel.exchange_declare(EXCHANGE_NAME, "direct")
        queueName = self.channel.queue_declare().method.queue

        self.channel.queue_bind(queueName, EXCHANGE_NAME, routing_key)

        # You may ask why we declare the queue again ‒ we have already declared it in our previous code.
        # We could avoid that if we were sure that the queue already exists. For example if send.py program
        # was run before. But we're not yet sure which program to run first. In such cases it's a good
        # practice to repeat declaring the queue in both programs.
        # self.channel.queue_declare(queue=queue)

        self.channel.basic_consume(callback,
                                   queue=queueName,
                                   no_ack=True)
        self.channel.start_consuming()

在work进程中用线程启动consumer,sel.uin这里是微信机器的id,作为channel的routing_key

class myWxbot():
    uin='botid_123'
    def start_consumer(self):
        td = threading.Thread(target=consumer, args=(str(self.uin),self.callback,))
        td.start()
    def callback(self, ch, method, properties, body):
        print 'receive cmd :%s'%body
    def proc_msg(self):
        while True:
                print "Bot loop"

celery task 发送端
routing_key这里应为对应wxbot 的uin

@task
def senderMsgToQueue(routing_key,body):
    EXCHANGE_NAME = "exchange_direct"

    credentials = pika.PlainCredentials('guest','guest')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '127.0.0.1',5672,'/',credentials))
    channel = connection.channel()

    # 声明queue
    # channel.queue_declare(queue=queue)
    channel.exchange_declare(EXCHANGE_NAME, "direct")
    # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
    channel.basic_publish(exchange=EXCHANGE_NAME,
                          routing_key=routing_key,
                          body=body)
    print(" [x] Sent 'Hello World!'")
    connection.close()

posted on 2017-07-05 09:18  chevsea  阅读(381)  评论(1)    收藏  举报

导航