简单队列模型
Queue
Queue(队列)是RabbitMQ的内部对象,用于存储消息,用下图表示。
RabbitMQ中的消息都只能存储在Queue中,生产者(下图中的P)生产消息并最终投递到Queue中,消费者(下图中的C)可以从Queue中获取消息并消费。
多个消费者可以订阅同一个Queue,这时Queue中的消息会被平均分摊给多个消费者进行处理,而不是每个消费者都收到所有的消息并处理。
编码实践
一、生产者和消费者模型
1、创建连接(生产端)
Connection connection = null;
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("youHost");
connectionFactory.setUsername("userName");
connectionFactory.setPassword("password");
connection = connectionFactory.newConnection();
2、创建channel(生产端)
Channel channel = connection.createChannel();
3、创建queue(生产端)
channel.queueDeclare("队列名称",false,false,false,null);
源码:
queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
Map<String, Object> arguments)
/**
* Construct a new queue, given a name, durability flag, and auto-delete flag, and arguments.
* @param name the name of the queue - must not be null; set to "" to have the broker generate the name.
* @param durable true if we are declaring a durable queue (the queue will survive a server restart)
* @param exclusive true if we are declaring an exclusive queue (the queue will only be used by the declarer's
* connection)
*