在下图的模型中,有以下概念:
- P:生产者,也就是要发送消息的程序。
- C:消费者,消息的接收者,会一直等待消息到来。
- queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。
需求: 使用简单模式完成消息传递
步骤:
(1)创建工程(生成者、消费者),分别添加依赖
(2)编写生产者发送消息
(3)编写消费者接收消息
一、生产者Module
(1)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>rabbitmq-demo</artifactId>
<groupId>net.xiaof</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>rabbitmq-producer</artifactId>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--rabbitmq java 客户端-->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(2)生产者类
package net.xiaof.producer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @author zhangxh
* @Description: 生产者
* @date 2020-12-13
*/
public class Producer_HelloWorld {
public static void main(String[] args) throws Exception {
//1.创建连接工厂,设置相关连接参数
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.116.161");
factory.setPort(5672);
factory.setVirtualHost("/myhost");
factory.setUsername("xiao");
factory.setPassword("xiao");
//2. 创建连接Connection
Connection connection = factory.newConnection();
//3. 创建Channel
Channel channel = connection.createChannel();
//4. 声明队列Queue
/**
* 【API说明】:
* queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
* 参数:
* (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
* (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
* (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
* (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
* (5)Map<String, Object> arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
*/
channel.queueDeclare("helloworld_queue", true, false, false, null);
//5. 发布消息
/**
* 【API说明】:
* basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
* 参数:
* (1)String exchange:交换机名称。简单模式下交换机会使用默认的 ""
* (2)String routingKey:路由名称
* (3)BasicProperties props:配置信息
* (4)byte[] body:发送消息数据
*/
String bodyMsg = "hello rabbitmq~~~好的";
channel.basicPublish("", "helloworld_queue", null, bodyMsg.getBytes());
//6. 关闭资源
channel.close();
connection.close();
}
}
二、消费者Module
(1)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>rabbitmq-demo</artifactId>
<groupId>net.xiaof</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>rabbitmq-consumer</artifactId>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--rabbitmq java客户端-->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(2)消费者类
package net.xiaof.consumer;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* @author zhangxh
* @Description: 消费者
* @date 2020-12-13
*/
public class Consumer_HelloWorld {
public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工厂,设置相关连接参数
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.116.161");
factory.setPort(5672);
factory.setVirtualHost("/myhost");
factory.setUsername("xiao");
factory.setPassword("xiao");
//2. 创建连接Connection
Connection connection = factory.newConnection();
//3. 创建Channel
Channel channel = connection.createChannel();
//4. 声明队列Queue
/**
* 【API说明】:
* queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
* 参数:
* (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
* (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
* (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
* (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
* (5)Map<String, Object> arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
*/
channel.queueDeclare("helloworld_queue", true, false, false, null);
//5. 接收消息
DefaultConsumer consumer = new DefaultConsumer(channel) {
/**
* 回调方法,当收到消息后,会自动执行该方法
* void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
* 参数:
* (1)String consumerTag:标识
* (2)Envelope envelope:获取一些信息,交换机,路由key...
* (3)AMQP.BasicProperties properties:配置信息
* (4)byte[] body:数据
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
System.out.println("consumerTag:" + consumerTag);
System.out.println("Exchange:" + envelope.getExchange());
System.out.println("RoutingKey:" + envelope.getRoutingKey());
System.out.println("properties:" + properties);
System.out.println("body:" + new String(body));
}
};
/**
* 【API说明】:
* basicConsume(String queue, boolean autoAck, Consumer callback)
* 参数:
* (1)String queue:队列名称
* (2)boolean autoAck:是否自动确认
* (3)Consumer callback:回调对象
*/
channel.basicConsume("helloworld_queue", true, consumer);
//6.关闭资源(消费者需要监听生产者消息,这里不关闭)
}
}
三、测试
(1)先启动消费者类,消费监听生产者消息。
(2)再启动生产者类生产消息,消费者消息消息,即控制台输出: