模型:
P:消息生产者
C:消费者
红色部分是消息队列
简单队列的使用
1、使用springboot,引入rabbitmq的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>1.5.19.RELEASE</version>
</dependency>
2、创建工具类获取连接
public class RabbitMqUtil {
public static Connection getConnection() throws IOException, TimeoutException {
//获取工厂,通过工厂创建连接
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.21.47");
factory.setPort(5672);
factory.setVirtualHost("/host1");
factory.setUsername("admin");
factory.setPassword("admin");
Connection conn = null;
conn = factory.newConnection();
return conn;
}
}
3、创建生产者
public class Provider {
private static final String QUNUE_NAME="test_qunue";
public static void main(String args[]) throws Exception {
//获取rabbitMQ连接
Connection conn = RabbitMqUtil.getConnection();
//创建channel
Channel channel = conn.createChannel();
//创建队列声明
channel.queueDeclare(QUNUE_NAME, false, false, false, null);
//发送消息
channel.basicPublish("", QUNUE_NAME, null, "hello world".getBytes());
channel.close();
conn.close();
}
}
4、创建消费者
public class Reciver {
private static final String QUNUE_NAME = "test_qunue";
public static void main(String[] args) throws Exception {
newApi();
}
public static void newApi()
throws Exception {
//获取连接
Connection conn = RabbitMqUtil.getConnection();
//创建channel
Channel channel = conn.createChannel();
//声明队列,如果生产者中声明了队列,消费者中可以不声明
//channel.queueDeclare(QUNUE_NAME, false, false, false, null);
//创建消费者
Consumer consumer = new DefaultConsumer(channel) {
//当生产者发送消息到rabbitmq之后,会自动触发消费者中的handleDelivery方法
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String msg = new String(body,"UTF-8");
System.out.println(msg);
}
};
//监听队列
channel.basicConsume(QUNUE_NAME, true, consumer);
}
/**
* 过期的方式
* @throws Exception
*/
public static void oldApi()
throws Exception {
Connection conn = RabbitMqUtil.getConnection();
Channel channel = conn.createChannel();
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUNUE_NAME, true, consumer);
while (true) {
Delivery delivery = consumer.nextDelivery();
String msg = new String(delivery.getBody());
System.out.println(msg);
}
}
}
简单队列模型耦合度高,生产者消费者一一对应,如果存在多个消费者,那么该模型则无法使用,队列名如果更改,那么消费者需要同步修改。