0

我从 websockets 开始,我对数字库和配置选项感到非常困惑。我只想设置一个项目,其中 node.js 服务器调用 python/django 中的方法,当最后一个完成时,它将结果传输回 node.js 服务器。这是我到目前为止所拥有的:

本教程中的 Nodes.js AMQP :

var conn = amqp.createConnection();
conn.on('ready', function(){
 var exchange = conn.exchange('?1', {'type': 'fanout', durable: false}, function() {
     exchange.publish('?2', {add: [1,2]});
 });
});

本教程中的 Django Celery :

from celery.decorators import task

@task()
def add(x, y):
   return x + y

我不知道这是否是要走的路,如果有人能阐明这个问题,我会很高兴。

---编辑

我成功地使用 AMQP 进行了简单的字符串传输:

测试.py

 import pika
 connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
 channel = connection.channel()

 channel.queue_declare(queue='task_queue', durable=True)

 print ' [*] Waiting for messages. To exit press CTRL+C'

 def callback(ch, method, props, body):
     print " [x] Received %r" % (body,)
     response = body + " MODIFIED"
     #response = get_a_concept()
     print " [x] Done"
     ch.basic_publish(exchange='',
                 routing_key=props.reply_to,
                 properties=pika.BasicProperties(correlation_id = \
                                                 props.correlation_id),
                 body=str(response))
     ch.basic_ack(delivery_tag = method.delivery_tag)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
                  queue='task_queue')

channel.start_consuming()

应用程序.js

 var connection = amqp.createConnection({ host: 'localhost' });
 connection.addListener('ready', function() {


var exchange = connection.exchange('', {
    'type' : 'direct',
    durable : false
}, function() {

    var queue = connection.queue('incoming', {
        durable : false,
        exclusive : true }, function() {
        queue.subscribe(function(msg) {
            console.log("received message: ");
            console.log(msg.data.toString());
        });

    });

    exchange.publish('task_queue', "it works!", {
        'replyTo' : 'incoming'
    });
});

});


不过,我不确定这是否是最好的实现,我什至没有在这里使用 queue.bind() 方法。当我尝试传递一个复杂的对象(json 甚至是一个简单的数组)时,就会出现问题。更改此行

 body= (["a","b","c"])#str(response)) 

导致以下错误:

 Traceback (most recent call last):
   File "test.py", line 56, in <module>
     channel.start_consuming()
   File "/Library/Python/2.7/site-packages/pika/adapters/blocking_connection.py", line 293, in      start_consuming
 (...)
   File "/Library/Python/2.7/site-packages/pika/simplebuffer.py", line 62, in write
     self.buf.write(data)
 TypeError: must be string or read-only character buffer, not list

有没有序列化复杂对象的解决方案?我错过了什么吗?

4

1 回答 1

0

正文必须是字节数组!

你必须二进制序列化你的对象。但是 nods.jss 和 pythons 可能不兼容。

python: pickle node.js:背包...

一个快速的解决方法可能是将您的数组加入到这样的字符串中:

测试.py

...
body = ';'.join(["a","b","c"]) # which will result in this string 'a;b;c'
...

并在您的app.js中将该字符串拆分为一个数组。

...
result = stringResult.split(';'); //stringResult is 'a;b;c'
...

另一种选择可能是在 node.js 中使用“异步”执行该异步任务

于 2012-08-14T07:09:31.040 回答