RabbitMQ学习笔记(1)
1、RabbitMQ安装
下载地址:http://www.rabbitmq.com/install-windows.html
详情百度一大把
2、简要介绍
根据官网:http://www.rabbitmq.com/getstarted.html
我们也以6种模式去介绍RabbitMQ的用法,如下:
- 快速入门Hello World
- 工作队列Work Queues
- 发布订阅Publish/Subscribe
- 路由Routing
- 主题Topics
- 远程过程调用RPC
每种模式均会参照文档以java代码的形式列出demo。
3、快速入门Hello World
P是生产者,C是消费者,中间是一个RabbitMQ消息队列。消息由生产者生产,传递给RabbitMQ,再由消费者消费。
pom.xml加入以下依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
</dependency>
发送端:
public class MqClient {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String message = "HelloWorld";
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println(" [x] sent '"+ message + "'");
channel.close();
connection.close();
}
}
点击运行,去本地mq监控端查看:
消费端:
public class MqServer {
private final static String QUEUE_NAME = “hello”;
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false,false,false,null);
System.out.println("[*] waiting for messages To exit Press CTRL + c");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println("[x] Received '"+ message + ",");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
}
}
点击运行,查看监控界面及控制台:
执行完成后,消费端线程会一直存在,用于监听生产端的生产。