入门构建消息生产以及消费
- Queue:具体的消息存储队列
- Producer& Consumer生产和消费者
具体代码实现
引入maven包
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.6.5</version>
</dependency>
消费端
public class Consumer {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.159");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
//4创建一个队列
channel.queueDeclare("test001",true,false,false,null);
//5创建一个消费者
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
//设置channel
channel.basicConsume("test001",true,queueingConsumer);
while (true){
//7获取消息
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
String msg = new String(delivery.getBody());
System.out.println("消费者" + msg);
Envelope envelope = delivery.getEnvelope();
}
}
}
生产者
public class Producter {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.159");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
//4通过Cchannel发送数据
for(int i=0;i<5;i++){
String msg = "HELLO";
channel.basicPublish("","test001",null,msg.getBytes());
}
channel.close();
connection.close();
}
}
- 启动Consumer 端,在RabbitMQ的控制台上可以看到创建的交换机以及队列。
- 启动Producter ,发送5条数据到Consumer ,在Consumer 控制台就可以看到接收到的消息。