1.简单模式:
P : 生产者
Queue(hello) : 队列
C : 消费者
步骤:
1.创建工程
2.分别添加RabbitMQ依赖
3.编写生产者发送消息
4.编写消费者获取消息
pom.xml
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.10.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>
producer(生产者):
public class Producer_helloworld {
private static final String QUEUE_NAME="queue";
public static void main(String[] args) throws IOException, TimeoutException {
//1获取连接工厂
ConnectionFactory factory = new ConnectionFactory();
//2设置参数
factory.setHost("127.0.0.1");//主机号
factory.setPort(5672);//端口号
factory.setVirtualHost("/test");//队列虚拟机
factory.setUsername("test");//用户名
factory.setPassword("test");//密码
//3创建连接Connection
Connection connection = factory.newConnection();
//4创建Channel
Channel channel = connection.createChannel();
//5创建队列
/*
queueDeclare(
String queue, 队列名称
boolean durable, 是否持久化到本地
boolean exclusive, (1)是否独占连接,只能有一个消费者监听这个队列(2)当connection关闭时,是否删除队列
boolean autoDelete, 是否自动删除,没有消费之自动删除
Map<String, Object> arguments) 配置参数
* */
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
/*
basicPublish(
String exchange, 交换机名称,简单模式使用默认交换机,空字符串即为默认交换机
String routingKey, 路由名称
BasicProperties props, 配置信息
byte[] body 发送的消息数据
)
*/
String body="傻逼java面试官";
//6发送消息
channel.basicPublish("",QUEUE_NAME,null,body.getBytes());
//7释放资源
/* if(channel != null){
channel.close();
}
if(connection != null){
connection.close();
}*/
}
}
consumer(消费者):
public class Hello01 {
private static final String QUEUE_NAME="queue";
public static void main(String[] args) throws IOException, TimeoutException {
//1获取连接工厂
ConnectionFactory factory = new ConnectionFactory();
//2设置参数
factory.setHost("127.0.0.1");//主机号
factory.setPort(5672);//端口号
factory.setVirtualHost("/test");//队列虚拟机
factory.setUsername("test");//用户名
factory.setPassword("test");//密码
//3创建连接Connection
Connection connection = factory.newConnection();
//4创建Channel
Channel channel = connection.createChannel();
//5创建队列
/*
queueDeclare(
String queue, 队列名称
boolean durable, 是否持久化到本地
boolean exclusive, (1)是否独占连接,只能有一个消费者监听这个队列(2)当connection关闭时,是否删除队列
boolean autoDelete, 是否自动删除,没有消费之自动删除
Map<String, Object> arguments) 配置参数
* */
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
/*
basicConsume(
String queue, 队列名
boolean autoAck, 是否自动确认
Consumer callback 回调函数
)
*/
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOExce