我的 RabbitMQ 订阅代码不起作用

My RabbitMQ subscription code doesn't work

我正在尝试从驻留在服务器上的 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 的新手。但是还有其他步骤或缺少什么吗?!为什么它不显示任何内容?

您的脚本运行良好。我使用交换 ProgressNotification 将一条消息推送到名为 simple_queue 的队列并打印了您的脚本。

b'Hello World!'

我使用了这个脚本,基于我自己的 RabbitMQ 库,但你可以只使用 this 鼠兔示例作为参考。

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 + "'");
        }
    }
}