(图片来自网络)
- Producer:生产者,负责生产消息以及投递消息到Exchange(交换机)
- Exchange:交换机,根据交换机类型的不同,按照不同的规则,通过RoutingKey(路由键)投递到某个Queue(队列)里
- RoutingKey:路由键,通过RoutingKey(路由键)将Queue(队列)与Exchange(交换机)Binding(绑定)在一起, Exchange(交换机)通过RoutingKey(路由键)将消息投递到某个Queue(队列)
- Queue:队列,消息都存放在Queue(队列)里,Exchange(交换机)通过RoutingKey(路由键)将消息投递到某个Queue(队列)
- Binding:绑定,通过RoutingKey(路由键)将Queue(队列)与Exchange(交换机)Binding(绑定)在一起
- Consumer:消费者,负责从Queue(队列)里取消息及消费消息
- Channel:信道。信道(Channel)是多路复用连接中的一条独立的双向数据流通道,消息发布接受订阅都依靠信道完成。
- Vhost:虚拟主机,即消息队列服务器实体
RabbitMQ的工作流程:
- 消息生产端简单代码发送消息(Producer_生产者):
public class Procuder {
public static void main(String[] args) throws Exception {
//1 创建一个ConnectionFactory, 并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.11.76");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2 通过连接工厂创建连接
Connection connection = connectionFactory.newConnection();
//3 通过connection创建一个Channel
Channel channel = connection.createChannel();
//4 通过Channel发送数据
for(int i=0; i < 5; i++){
String msg = "Hello RabbitMQ!";
//1 exchange 2 routingKey
channel.basicPublish("", "test001", null, msg.getBytes());
}
//5 记得要关闭相关的连接
channel.close();
connection.close();
}
}
- 消息消费端接收消息(Consumer_消费者)
public class Consumer {
public static void main(String[] args) throws Exception {
//1 创建一个ConnectionFactory, 并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.11.76");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2 通过连接工厂创建连接
Connection connection = connectionFactory.newConnection();
//3 通过connection创建一个Channel
Channel channel = connection.createChannel();
//4 声明(创建)一个队列
String queueName = "test001";
channel.queueDeclare(queueName, true, false, false, null);
//5 创建消费者
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
//6 设置Channel
channel.basicConsume(queueName, true, queueingConsumer);
while(true){
//7 获取消息
Delivery delivery = queueingConsumer.nextDelivery();
String msg = new String(delivery.getBody());
System.err.println("消费端: " + msg);
//Envelope envelope = delivery.getEnvelope();
}
}
}