安装
# 拉取镜像
docker pull rabbitmq:management
# 创建容器
docker run -e RABBIT_DEFAULT_USER=root -e RABBIT_DEFAULT_PASS=root --name rabbitmq_mg -p 15672:15672 -p 5672:5672 -d rabbitmq:management
# 访问管理页面
# http://10.10.0.100:15672
# root:root(如果登录失败,则选择guest:guest)
使用AMQP的Java客户端编程实现消息的发送和接收
1.新建maven项目
pom文件引入amqp的依赖
<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.9.0</version>
</dependency>
2.发布消息
PublisherTest.java
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("10.10.0.100");
factory.setPort(5672);
factory.setVirtualHost("/");
factory.setUsername("guest");
factory.setPassword("guest");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String message = scanner.next();
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println("[x]发送'" + message + "'");
}
channel.close();
connection.close();
3.消费消息
ConsumerTest.java
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("10.10.0.100");
factory.setPort(5672);
factory.setVirtualHost("/");
factory.setUsername("guest");
factory.setPassword("guest");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicConsume(QUEUE_NAME, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws
IOException {
//处理消息
String message = new String(body);
System.out.println(" [x] Received '" + message + "'");
}
});
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");