RabbitMQ的模型
1:第一种模型(直连)
- P:生产者,也就是要发送消息的程序
- C:消费者:消息的接受者,会一直等待消息到来。
- queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。
2:代码实现
1,新建一个maven项目
pom.xml导入依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.2</version>
</dependency>
2,封装RabbitMMQUtils工具类
public class RabbitMQUtils {
//只创建一次,类加载时执行,只执行一次
//重量级资源
private static ConnectionFactory connectionFactory;
static{
//创建连接mq的连接工厂对象
connectionFactory = new ConnectionFactory();
//设置连接RabbitMQ的主机
connectionFactory.setHost("192.168.0.27");
//设置端口号
connectionFactory.setPort(5672);
//设置连接哪个虚拟主机
connectionFactory.setVirtualHost("/shop");
//设置访问虚拟主机的用户名密码
connectionFactory.setUsername("shop");
connectionFactory.setPassword("123456");
}
//定义提供链接对象的方法
public static Connection getConnection(){
try{
//重量级资源
return connectionFactory.newConnection();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
//关闭通道和关闭连接工具的方法
public static void closeConnectionAndChanel(Channel channel,Connection connection){
try{
if(channel!=null){
channel.close();
}
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
3:开发生产者
public class Provider {
//生产消息
@Test
public void testSendMessage() throws IOException {
//工具类获取连接对象
Connection connection1 = RabbitMQUtils.getConnection();
//获取连接中的通道对象
Channel channel = connection1.createChannel();
//通道绑定对应的消息队列
//参数1:队列名称(如果队列不存在自动创建)
//参数2:用来定义队列的特性是否要持久化 true为持久化队列,false为不持久化队列
//参数3: exclusive 是否独占队列 true代表独占队列,false为不独占
//参数4: autoDelete 是否在消费完成后自动删除队列,true为自动删除,false不自动删除
//参数5:额外附加参数
channel.queueDeclare("hello",false,false,false,null);
//发布消息
//参数1:交换机名称
//参数2:队列名称
//参数3:传递消息额外设置 MessageProperties.PERSISTENT_BASIC消息持久化
//参数4:消息的具体内容
channel.basicPublish("","hello",null,"hello rabbitmq".getBytes());
RabbitMQUtils.closeConnectionAndChanel(channel,connection1);
//关闭通道
/* channel.close();
//关闭连接
connection.close();*/
}
}
4:开发消费者
public class Customer {
public static void main(String[] args) throws IOException {
//工具类获取连接对象
Connection connection = RabbitMQUtils.getConnection();
//创建通道
Channel channel = connection.createChannel();
//通道绑定队列
channel.queueDeclare("hello",false,false,false,null);
//消费消息
//参数1:消费哪个队列的消息 队列名称
//参数2:开始消息的自动确认机制
//参数3:消费消息的回调接口
channel.basicConsume("hello",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) = "+new String(body));
}
});
//Customer端不建议关闭连接
//channel.close();
//connection.close();
}
}
(注意:生产者与消费者调用方法参数需要保持一致)
5:junit测试