我从 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
有没有序列化复杂对象的解决方案?我错过了什么吗?