我正在尝试从服务器上的RabbitMQ
接收通知。有人告诉我使用此代码,该代码应打印进度通知。但是,当运行代码并将作业提交到队列时,我什么也没看到。该代码不输出任何内容:
import pika
rabbitMqHost = 'host'
rabbitMqUser = 'user'
rabbitMqPass = 'password'
exchangeName = 'ProgressNotification'
credentials = pika.PlainCredentials(rabbitMqUser, rabbitMqPass)
connection = pika.BlockingConnection(pika.ConnectionParameters(rabbitMqHost, 5672, '/', credentials))
channel = connection.channel()
# channel.exchange_delete(exchange=exchangeName)
# exit(3)
channel.exchange_declare(exchange=exchangeName, exchange_type='fanout')
result = channel.queue_declare()
queue_name = result.method.queue
channel.queue_bind(exchange=exchangeName,
queue=queue_name)
def callback(ch, method, properties, body):
print("> %r" % (body,))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
抱歉,我是RabbitMQ
的新手。但是还有其他步骤或缺少什么吗?为什么它什么都不显示?
答案 0 :(得分:1)
您的脚本工作正常。我使用交换机ProgressNotification
将消息推送到名为simple_queue的队列,并打印了您的脚本。
b'Hello World!'
我基于我自己的RabbitMQ库使用了此脚本,但是您可以仅使用this pika示例作为参考。
from amqpstorm import Connection
from amqpstorm import Message
with Connection('127.0.0.1', 'guest', 'guest') as connection:
with connection.channel() as channel:
# Declare the Queue, 'simple_queue'.
channel.queue.declare('simple_queue')
# Create the message.
message = Message.create(channel, 'Hello World!')
# Publish the message to a queue called, 'simple_queue'.
message.publish('simple_queue', exchange='ProgressNotification')
在Java中,您需要像这样发布消息。
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Send {
private final static String QUEUE_NAME = "simple_queue";
private final static String EXCHANGE_NAME = "ProgressNotification";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}
}
}