RabbitMQ 提供了 6 种工作模式:简单模式、work queues、Publish/Subscribe 发布与订阅模式、Routing 路由模式、Topics 主题模式、RPC 远程调用模式(远程调用,不太算 MQ;暂不作介绍)。
官网对应模式介绍:https://www.rabbitmq.com/getstarted.html
在上图的模型中,有以下概念:
P:生产者,也就是要发送消息的程序
C:消费者:消息的接收者,会一直等待消息到来
queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.14.2</version>
</dependency>
</dependencies>
package com.lzq.jd;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Aproduct {
public static void main(String[] args) throws Exception {
//创建连接工厂类并设置连接信息
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.179.129");//设置rabbitmq服务的地址 默认localhost
factory.setPort(5672);//设置rabbitmq的端口号 AMQP端口号
factory.setUsername("user");//设置账号 默认guest
factory.setPassword("123456");// 设置密码 默认guest
factory.setVirtualHost("/aaa");//设置虚拟主机 默认/
//连接对象
Connection connection = factory.newConnection();
//获取channel对象
Channel channel = connection.createChannel();
//创建队列
/*
* String queue,队列的名称,如果该名称不存在则创建 如果存在则不创建
* boolean durable, 该对象是否持久化 当rabbitmq重启后 队列就会消失
* boolean exclusive,该队列是否被一个消费者独占
* boolean autoDelete,当没有消费者时 该队列是否被自动删除
* Map arguments 额外参数的设置
*
* */
channel.queueDeclare("lzq_queue",true,false,false,null);
//发送消息
String msg = "你好,阿娇";
channel.basicPublish("","lzq_queue",null,msg.getBytes());
//关闭资源
channel.close();
connection.close();
}
}
package com.lzq.jd;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Bconsumer {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setVirtualHost("/aaa");
factory.setUsername("user");
factory.setPassword("123456");
factory.setHost("192.168.179.129");
factory.setPort(5672);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("lzq_queue",true,false,false,null);
//接收队列中的消息
DefaultConsumer consumer = new DefaultConsumer(channel){
/*
* consumerTag:消费者的标签
* envelope:设置 拿到你的交换机 路由key等信息
* properties:消息的属性对象
* body:消息内容
*
* */
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容:"+new String(body));
System.out.println("消费者的标志"+consumerTag);
System.out.println("交换机名称"+envelope.getExchange());
System.out.println("路由key标志"+envelope.getRoutingKey());
System.out.println("消息属性"+properties);
}
};
/*
* string queue, 队列名
* boolean autoAck 是否自动确认 当rabbitmq把消息发送给消息后 消息端自动确认消息
* Consumer callback 回调 当rabbitmq队列中存在消息则触发该回调
* */
channel.basicConsume("lzq_queue",true,consumer);
//是否要关闭connection和channel ---不能关闭 关闭不会一直监听消息
}
}
Work Queues:与入门程序的简单模式相比,多了一个或一些消费端,多个消费端共同消费同一个队列中的消息。
应用场景:对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。
package com.lzq.gz;
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 Aproduct {
public static void main(String[] args) throws Exception {
//创建连接工厂类并设置连接信息
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.179.129");
factory.setPort(5672);
factory.setUsername("user");
factory.setPassword("123456");
factory.setVirtualHost("/aaa");
//连接对象
Connection connection = factory.newConnection();
//获取channel对象
Channel channel = connection.createChannel();
//创建队列
channel.queueDeclare("gz_queue",true,false,false,null);
//发送消息
for (int i =0; i<10;i++) {
String msg = "你好,阿娇";
channel.basicPublish("", "gz_queue", null, msg.getBytes());
}
//关闭资源
channel.close();
connection.close();
}
}
package com.lzq.gz;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Bconsumer {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setVirtualHost("/aaa");
factory.setUsername("user");
factory.setPassword("123456");
factory.setHost("192.168.179.129");
factory.setPort(5672);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("gz_queue", true, false, false, null);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接收的内容" + new String(body));
}
};
channel.basicConsume("gz_queue", true, consumer);
}
}
消费者2
package com.lzq.gz;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Bconsumer2 {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setPort(5672);
factory.setUsername("user");
factory.setPassword("123456");
factory.setVirtualHost("/aaa");
factory.setHost("192.168.179.129");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容"+new String(body));
}
};
channel.basicConsume("gz_queue",true,consumer);
}
}
总结: 在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是竞争的关系。
Work Queues 对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。例如:短信服务部署多个,只需要有一个节点成功发送即可。
在订阅模型中,多了一个 Exchange 角色,而且过程略有变化:
Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange 绑定,或者没有符合路由规则的队列,那么消息会丢失!
package com.lzq.dy;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import javafx.scene.control.TextFormatter;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Aproduct {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.179.129");
factory.setPort(5672);
factory.setUsername("user");
factory.setPassword("123456");
factory.setVirtualHost("/aaa");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//创建交换机
/*
* string exchange 交换机的名称 如果不存在则创建 存在则不创建
* BuiltinExchangeType 交换机的类型
* boolean durable 是否持久化
* */
channel.exchangeDeclare("dy_exchange", BuiltinExchangeType.FANOUT,true);
//创建队列
channel.queueDeclare("dy_queue01",true,false,false,null);
channel.queueDeclare("dy_queue02",true,false,false,null);
//队列和交换机进行绑定
/*
* string queue 队列名
* string exchange 交换机名
* string routingkey: 发布订阅模式 没有routingkey 则写为""
* */
channel.queueBind("dy_queue01","dy_exchange","");
channel.queueBind("dy_queue02","dy_exchange","");
String mag = "你好 阿娇";
channel.basicPublish("dy_exchange","",null,mag.getBytes());
channel.close();
connection.close();
}
}
消费者1
package com.lzq.dy;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Bconsumer1 {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("user");
factory.setPassword("123456");
factory.setPort(5672);
factory.setVirtualHost("/aaa");
factory.setHost("192.168.179.129");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容"+new String(body));
}
};
channel.basicConsume("dy_queue01",true,consumer);
}
}
消费者2
package com.lzq.dy;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Bconsumer2 {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.179.129");
factory.setPort(5672);
factory.setUsername("user");
factory.setPassword("123456");
factory.setVirtualHost("/aaa");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容"+new String(body));
}
};
channel.basicConsume("dy_queue02",true,consumer);
}
}
交换机需要与队列进行绑定,绑定之后;一个消息可以被多个消费者都收到。
发布订阅模式与工作队列模式的区别:
package com.lzq.lu;
import com.rabbitmq.client.BuiltinExchangeType;
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 Aproduct {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("user");
factory.setPassword("123456");
factory.setPort(5672);
factory.setVirtualHost("/aaa");
factory.setHost("192.168.179.129");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("lu_exchange", BuiltinExchangeType.DIRECT,true);
channel.queueDeclare("lu_queue01",true,false,false,null);
channel.queueDeclare("lu_queue02",true,false,false,null);
channel.queueBind("lu_queue01","lu_exchange","error");
channel.queueBind("lu_queue02","lu_exchange","error");
channel.queueBind("lu_queue02","lu_exchange","info");
channel.queueBind("lu_queue02","lu_exchange","warning");
String msg = "你好,阿娇";
channel.basicPublish("lu_exchange","error",null,msg.getBytes());
channel.close();
connection.close();
}
}
消费者1
package com.lzq.lu;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Bconsumer1 {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("user");
factory.setPassword("123456");
factory.setPort(5672);
factory.setVirtualHost("/aaa");
factory.setHost("192.168.179.129");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容"+new String(body));
}
};
channel.basicConsume("lu_queue01",true,consumer);
}
}
消费者2
package com.lzq.lu;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Bconsumer2 {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.179.129");
factory.setPort(5672);
factory.setUsername("user");
factory.setPassword("123456");
factory.setVirtualHost("/aaa");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容"+new String(body));
}
};
channel.basicConsume("lu_queue02",true,consumer);
}
}
小结:
Routing 模式要求队列在绑定交换机时要指定 routing key,消息会转发到符合 routing key 的队列。
package com.lzq.zt;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import javafx.scene.control.TextFormatter;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Aproduct {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.179.129");
factory.setPort(5672);
factory.setUsername("user");
factory.setPassword("123456");
factory.setVirtualHost("/aaa");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("zt_exchange", BuiltinExchangeType.TOPIC,true);
channel.queueDeclare("zt_queue01",true,false,false,null);
channel.queueDeclare("zt_queue02",true,false,false,null);
channel.queueBind("zt_queue01","zt_exchange","*.aaa");
channel.queueBind("zt_queue02","zt_exchange","*.aaa.*");
channel.queueBind("zt_queue02","zt_exchange","aaa.#");
String msg = "你好,阿娇";
channel.basicPublish("zt_exchange","b.aaa",null,msg.getBytes());
channel.close();
connection.close();
}
}
消费者1
package com.lzq.zt;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Bconsumer1 {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("user");
factory.setPassword("123456");
factory.setPort(5672);
factory.setVirtualHost("/aaa");
factory.setHost("192.168.179.129");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容"+new String(body));
}
};
channel.basicConsume("zt_queue01",true,consumer);
}
}
package com.lzq.zt;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Bconsumer2 {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.179.129");
factory.setPort(5672);
factory.setUsername("user");
factory.setPassword("123456");
factory.setVirtualHost("/aaa");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接受的内容"+new String(body));
}
};
channel.basicConsume("zt_queue02",true,consumer);
}
}
Topic 主题模式可以实现 Pub/Sub 发布与订阅模式和 Routing 路由模式的功能,只是 Topic 在配置routing key 的时候可以使用通配符,显得更加灵活。