1.创建虚拟主机
编写代码之前我们先在rabbitmq的管理界面上创建一个虚拟主机/test
2.pom.xml中引入rabbitmq的依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.3</version>
</dependency>
3.编写消息生产者
package com.chenf24k.rabbitmq.helloworld;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
public static void main(String[] args) throws IOException, TimeoutException {
// 创建MQ的物理连接
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/test");
// TCP 物理连接
Connection connection = factory.newConnection();
// 通信通道,虚拟连接
Channel channel = connection.createChannel();
// 参数一:队列名称
// 参数二:是否持久化
// 参数三:队列是否私有化
// 参数四:连接停掉后是否自动删除这个队列
channel.queueDeclare("helloworld", false, false, false, null);
// 参数一:exchange交换机,此处暂时不用
// 参数二:队列名称
// 参数三:额外的设置属性
// 参数四:数据的字节数组
String message = "Hello,World!";
channel.basicPublish("", "helloworld", null, message.getBytes());
channel.close();
connection.close();
System.out.println("发送数据成功");
}
}
4.创建消费者
package com.chenf24k.rabbitmq.helloworld;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Consumer {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/test");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("helloworld", false, false, false, null);
// 创建一个消息消费者
// 参数一:队列名称
// 参数二:是否自动确认收到消息
// 参数三:传入DefaultConsumer的实现类
channel.basicConsume("helloworld", false, new Receiver(channel));
}
}
class Receiver extends DefaultConsumer {
private Channel channel;
// 重写构造函,Channel通道对象需要从外部传入,在handleDelivery中要用到
public Receiver(Channel channel) {
super(channel);
this.channel = channel;
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String messageBody = new String(body);
System.out.println("消费者接收到:" + messageBody);
// 签收消息
// envelope.getDeliveryTag() 获取这个消息的TagId()
// false 只确认签收当前的消息, true 时则代表签收该消费者所有未签收的消息
channel.basicAck(envelope.getDeliveryTag(), false);
}
}
控制台输出: