RabbitMQ入门(java)
在这里我就放出官方的例子
首先需要创建一个channel,官方创建方式如下:
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("localhost");
factory.setPort(5672);
官网的创建channel的链接:创建channel链接
生产者创建消息:
//QUEUE_NAME为你要创建的消息队列名称
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
消费者消费消息:
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
//QUEUE_NAME为你要接受的消息队列名称
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
下面是我测试的完整代码:
生产者:
package com.rg1b;
import com.rabbitmq.client.*;
public class RabbitMQCeshi {
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
// "guest"/"guest" by default, limited to localhost connections
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("localhost");
factory.setPort(5672);
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
// channel.exchangeDeclare("宋A", "direct", true);
channel.queueDeclare("宋A的队列", false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", "宋A的队列", null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
// channel.basicPublish("宋A", "软工一班", true,
// MessageProperties.PERSISTENT_TEXT_PLAIN,
// messageBodyBytes);
}
}
消费者:
package com.rg1b;
import com.rabbitmq.client.*;
import java.io.IOException;
public class RabbitMQConsumer {
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("localhost");
factory.setPort(5672);
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume("宋志锋的队列", true, deliverCallback, consumerTag -> { });
}
}