1.模型图
- p:代表的是生产者
- c:代表的是消费者
实现过程:生产者将消息发送到队列中,消费者从队列中获取消息进行消费
2.实现代码
工具类
public class MqUtil {
// 创建连接工厂
private static final ConnectionFactory factory = new ConnectionFactory();
static {
// 设置连接mq的主机
factory.setHost("192.168.175.159");
// 设置连接端口号
factory.setPort(5672);
// 设置连接的虚拟主机
factory.setVirtualHost("javatest");
// 设置访问虚拟主机的用户名
factory.setUsername("javatest");
// 设置访问虚拟主机的密码
factory.setPassword("javatest");
}
// 获取连接
public static Connection getConnection(){
try {
return factory.newConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return null;
}
// 关闭资源
public static void close(Channel channel,Connection connection){
try {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
生产者
1.代码展示
public class Send {
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = MqUtil.getConnection();
// 通过连接去创建传输数据的通道
Channel channel = connection.createChannel();
// 将通道与队列绑定
/*
* 参数1:绑定的队列名,没有则创建
* 参数2:是否持久化,队列默认是放在内存中的,rabbitmq服务挂了队列被删除,设置为true则持久化到磁盘,rabbitmq服务挂了重启还存在
* 参数3:是否独占,设置为true表示独占,一般用于一个生产者和一个消费者场景,当连接关闭时会删除该队列。
* 参数4:是否自动删除,自动删除前提是之前有消费者,当消费者全部断开连接后,则自动删除
* 参数5:对队列长度和队列里面的消息进行设置
* */
channel.queueDeclare("helloworld",true,false,false,null);
// 发布消息
/*
* 参数1:交换机名称,该模式下不需要
* 参数2:路由键,由于没有交换机,此时是将消息发布到的队列名
* 参数3:发送消息的额外设置
* 参数4:发送消息的内容,需要是字节类型
* */
channel.basicPublish("","helloworld", MessageProperties.PERSISTENT_TEXT_PLAIN,"rabbitmq".getBytes());
MqUtil.close(channel,connection);
}
}
2.queueDeclare方法的详解
链接:link
3.basicPublish方法的详解
链接:link
消费者
1.代码展示
public class Recv {
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = MqUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("helloworld",true,false,false,null);
// 消费消息
/*
* 参数1:队列名
* 参数2:开启自动确认机制
* 参数3:消息的回调接口,创建Consumer接口的实现类DefaultConsumer,重写handleDelivery方法,去处理队列中的数据
* */
String helloworld = channel.basicConsume("helloworld", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
// 关闭连接,一般消费者不关闭,一直监听队列消息并消费
// MqUtil.close(channel,connection);
}
}