我有一个Java程序,它向RabbitMQ发送消息。我所知道的只是交换名称。没有队列,绑定等。
我的问题是:如何知道程序是否成功发送,只知道交换名称?
感谢。
此致 谢尔班
答案 0 :(得分:2)
您可以使用RabbitMQ启用publisher confirmation。它就像发送事务一样,RabbitMQ会告诉你消息是否成功发送。
答案 1 :(得分:0)
请看这里:https://www.rabbitmq.com/tutorials/tutorial-three-java.html
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "");
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(queueName, true, consumer);
简而言之,你必须:
在exchange
或fanout
或topic
direct
的类型非常重要
在此示例中为fanout
答案 2 :(得分:0)
假设我们有RabbitMQ Exchange,我们需要创建一个队列来将消息推送到交换机并从队列中消耗它,如下所示
private static final String EXCHANGE_NAME = "2022"; private static final String QUEUE_NAME = "2022"; private final static boolean durable = true; // now we need to create a connection to rabbitmq server // ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); factory.setHost("127.0.0.1"); factory.setPort(5672); Connection conn = factory.newConnection(); // create rabbitmq connection chaneel Channel channel = conn.createChannel(); //Declare Exchange // channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); // push message to rabbitmq exchange channel.basicPublish(EXCHANGE_NAME, "routingkey", null, yourmessage.getBytes());
以上作为制作人的工作现在我们需要创建队列消费者
private static final String EXCHANGE_NAME = "2022"; private static final String QUEUE_NAME = "2022"; private final static boolean durable = true; // now we need to create a connection to rabbitmq server // ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); factory.setHost("127.0.0.1"); factory.setPort(5672); Connection conn = factory.newConnection(); // create rabbitmq connection chaneel Channel channel = conn.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); //Queue Declare // channel.queueDeclare(QUEUE_NAME, true, false, false, null); //Queue bind // channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "routingkey"); // Queue Consume // QueueingConsumer consumer = new QueueingConsumer(channel); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); }