前面2个案例中,只有3个角色:
P:生产者,也就是要发送消息的程序
C:消费者:消息的接受者,会一直等待消息到来。
queue:消息队列,图中红色部分
而在订阅模型中,多了一个exchange角色,而且过程略有变化:
P:生产者,也就是要发送消息的程序,但是不再发送到队列中,而是发给X(交换机)
C:消费者,消息的接受者,会一直等待消息到来。
Queue:消息队列,接收消息、缓存消息。
Exchange:交换机,图中的X。一方面,接收生产者发送的消息。另一方面,知道如何处理消息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作,取决于Exchange的类型。Exchange有常见以下3种类型:
Fanout:广播,将消息交给所有绑定到交换机的队列
Direct:定向,把消息交给符合指定routing key 的队列
Topic:通配符,把消息交给符合routing pattern(路由模式) 的队列
Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!
Publish/Subscribe发布与订阅模式
发布订阅模式:
1、每个消费者监听自己的队列。
2、生产者将消息发给broker,由交换机将消息转发到绑定此交换机的每个队列,每个绑定交换机的队列都将接收 到消息。
代码演示
消息生产者
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 ProducerPubSubMain {
public static void main(String[] args) throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置参数
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("/itcast");
factory.setUsername("wujian");
factory.setPassword("wujian");
//创建连接
Connection connection =factory.newConnection();
//创建通道
Channel channel =connection.createChannel();
/** public DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal,Map<String, Object> arguments) throws IOException {
return this.exchangeDeclare(exchange, type.getType(), durable, autoDelete, arguments);
String exchange 交换机名称
BuiltinExchangeType type 交换机类型
DIRECT("direct"), 点对点交换机
FANOUT("fanout"), 广播形式的交换机
TOPIC("topic"), 通配符形式的交换机
HEADERS("headers"); 很少用不做学习
boolean durable 是否持久化
boolean autoDelete 是否自动删除
boolean internal 内部 一般设置为false
Map<String, Object> arguments 参数
}*/
String exchangeName="message_exchange";
//创建交换机
channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false,null);
//创建队列
String alibaba = "alibaba";
String microsoft = "microsoft";
/** public com.rabbitmq.client.AMQP.Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
queue 队列的名称
durable 是否持久化,当mq重启之后还在
exclusive 是否独占,只有一个消费者监听这个队列
当connection 关闭的时候删除这个队列
autoDelete 是否自动删除,没有消费者的时候删除
arguments 参数
}*/
channel.queueDeclare(alibaba,true,false,false,null);
channel.queueDeclare(microsoft,true,false,false,null);
/**queueBind(String queue, String exchange, String routingKey)
* queue 队列名称
* exchange 交换机名称
* routingKey 路由key
* 如果交换机是 fanout就设置为空字符串
* */
// 绑定交换机和队列
channel.queueBind(alibaba,exchangeName,"");
channel.queueBind(microsoft,exchangeName,"");
String body = "日志信息:日志级别很低";
/**public void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException {
exchange 交换机名称,简单模式下的交换机会默认使用 ""
routingKey 路由名称
props 配置信息
body 消息体
*/
channel.basicPublish(exchangeName,"",null,body.getBytes());
//释放资源
channel.close();
connection.close();
}
}
消息消费者1
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class ConsumerPubSub {
public static void main(String[] args) throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置参数
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("/itcast");
factory.setUsername("wujian");
factory.setPassword("wujian");
//创建连接
Connection connection =factory.newConnection();
Channel channel =connection.createChannel();
String alibaba = "alibaba";
// 创建 queue
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 {
super.handleDelivery(consumerTag, envelope, properties, body);
// System.out.println("标识:" + consumerTag);
// System.out.println("一些信息" + envelope.getExchange());
// System.out.println("这个是路由,其实是队列名称" + envelope.getRoutingKey());
// System.out.println("消息序号" + envelope.getDeliveryTag());
// System.out.println("配置信息:" + properties);
System.out.println("消息" + new String(body));
System.out.println("阿里巴巴有优惠了赶快消费哦");
}
};
channel.basicConsume(alibaba, true, consumer);
}
}
消息消费者2
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class ConsumerPubSub1 {
public static void main(String[] args) throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置参数
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("/itcast");
factory.setUsername("wujian");
factory.setPassword("wujian");
//创建连接
Connection connection =factory.newConnection();
Channel channel =connection.createChannel();
String alibaba = "microsoft";
// 创建 queue
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 {
super.handleDelivery(consumerTag, envelope, properties, body);
// System.out.println("标识:" + consumerTag);
// System.out.println("一些信息" + envelope.getExchange());
// System.out.println("这个是路由,其实是队列名称" + envelope.getRoutingKey());
// System.out.println("消息序号" + envelope.getDeliveryTag());
// System.out.println("配置信息:" + properties);
System.out.println("消息" + new String(body));
System.out.println("微软有优惠了赶快消费哦");
}
};
channel.basicConsume(alibaba, true, consumer);
}
}
测试结果
启动所有消费者,然后使用生产者发送消息;在每个消费者对应的控制台可以查看到生产者发送的所有消息;到达广播的效果。
总结
交换机需要与队列进行绑定,绑定之后;一个消息可以被多个消费者都收到。
发布订阅模式与工作队列模式的区别
1、工作队列模式不用定义交换机,而发布/订阅模式需要定义交换机。
2、发布/订阅模式的生产方是面向交换机发送消息,工作队列模式的生产方是面向队列发送消息(底层使用默认交换机)。
3、发布/订阅模式需要设置队列和交换机的绑定,工作队列模式不需要设置,实际上工作队列模式会将队列绑 定到默认的交换机 。