RabbitMQ Exchange分发消息时根据类型的不同分发策略有区别,目前共四种类型:direct、fanout、topic、headers 。headers 匹配 AMQP 消息的 header 而不是路由键,此外 headers 交换器和 direct 交换器完全一致,但性能差很多,目前几乎用不到了。下面分别以实例的方式对这几种exchange进行讲解。

direct

  首先我们以路由的方式对消息进行过滤,代码如下:

生产者

 public class RoutingSendDirect {

     private static final String EXCHANGE_NAME = "direct_test";

     private static final String[] routingKeys = new String[]{"info" ,"warning", "error"};

     public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localhost");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"direct");
for(String key : routingKeys){
String message = "RoutingSendDirect Send the message level:" + key;
channel.basicPublish(EXCHANGE_NAME,key,null,message.getBytes());
System.out.println("RoutingSendDirect Send"+key +"':'" + message);
}
channel.close();
connection.close();
}
}

消费者

 public class ReceiveDirect1 {
// 交换器名称
private static final String EXCHANGE_NAME = "direct_test";
// 路由关键字
private static final String[] routingKeys = new String[]{"info" ,"warning"}; public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localhost");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"direct");
//获取匿名队列名称
String queueName=channel.queueDeclare().getQueue();
for(String key : routingKeys){
channel.queueBind(queueName,EXCHANGE_NAME,key);
System.out.println("ReceiveDirect1 exchange:"+EXCHANGE_NAME+"," +
" queue:"+queueName+", BindRoutingKey:" + key);
} System.out.println("ReceiveDirect1 Waiting for messages");
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body,"UTF-8");
System.out.println("ReceiveDirect1 Received '" + envelope.getRoutingKey() + "':'" + msg + "'");
}
}; channel.basicConsume(queueName, true, consumer);
}
}
 public class ReceiveDirect2 {
// 交换器名称
private static final String EXCHANGE_NAME = "direct_test";
// 路由关键字
private static final String[] routingKeys = new String[]{"error"}; public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localhost");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"direct");
//获取匿名队列名称
String queueName=channel.queueDeclare().getQueue();
for(String key : routingKeys){
channel.queueBind(queueName,EXCHANGE_NAME,key);
System.out.println("ReceiveDirect2 exchange:"+EXCHANGE_NAME+"," +
" queue:"+queueName+", BindRoutingKey:" + key);
} System.out.println("ReceiveDirect2 Waiting for messages");
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body,"UTF-8");
System.out.println("ReceiveDirect2 Received '" + envelope.getRoutingKey() + "':'" + msg + "'");
}
}; channel.basicConsume(queueName, true, consumer);
}
}

运行结果如下:

 RoutingSendDirect Sendinfo':'RoutingSendDirect Send the message level:info
RoutingSendDirect Sendwarning':'RoutingSendDirect Send the message level:warning
RoutingSendDirect Senderror':'RoutingSendDirect Send the message level:error ReceiveDirect1 exchange:direct_test, queue:amq.gen-HsUrzbjzto-K7HeigXSEfQ, BindRoutingKey:info
ReceiveDirect1 exchange:direct_test, queue:amq.gen-HsUrzbjzto-K7HeigXSEfQ, BindRoutingKey:warning
ReceiveDirect1 Waiting for messages
ReceiveDirect1 Received 'info':'RoutingSendDirect Send the message level:info'
ReceiveDirect1 Received 'warning':'RoutingSendDirect Send the message level:warning' ReceiveDirect2 exchange:direct_test, queue:amq.gen-i3NY12l3DqWjGapaBOCdwQ, BindRoutingKey:error
ReceiveDirect2 Waiting for messages
ReceiveDirect2 Received 'error':'RoutingSendDirect Send the message level:error'

fanout

  fanout和别的MQ的发布/订阅模式类似,实例如下:

生产者  

 public class Pub {
private static final String EXCHANGE_NAME = "logs";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory=new ConnectionFactory();
factory.setHost("localhost");
Connection connection=factory.newConnection();
Channel channel=connection.createChannel();
//fanout表示分发,所有的消费者得到同样的队列信息
channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
//分发信息
for (int i=;i<;i++){
String message="Hello World"+i;
channel.basicPublish(EXCHANGE_NAME,"",null,message.getBytes());
System.out.println("Pub Sent '" + message + "'");
}
channel.close();
connection.close();
}
}

消费者

public class Sub {
private static final String EXCHANGE_NAME = "logs"; public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); //产生一个随机的队列名称
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "");//对队列进行绑定 System.out.println("Sub Waiting for messages");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println("Sub Received '" + message + "'");
}
};
channel.basicConsume(queueName, true, consumer);//队列会自动删除
}
}

Topics

这种应该属于模糊匹配,* :可以替代一个词,#:可以替代0或者更多的词,现在我们继续看看代码来理解

生产者  

 public class TopicSend {
private static final String EXCHANGE_NAME = "topic_logs"; public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = null;
Channel channel = null;
try{
ConnectionFactory factory=new ConnectionFactory();
factory.setHost("localhost");
connection=factory.newConnection();
channel=connection.createChannel(); //声明一个匹配模式的交换机
channel.exchangeDeclare(EXCHANGE_NAME,"topic");
//待发送的消息
String[] routingKeys=new String[]{
"quick.orange.rabbit",
"lazy.orange.elephant",
"quick.orange.fox",
"lazy.brown.fox",
"quick.brown.fox",
"quick.orange.male.rabbit",
"lazy.orange.male.rabbit"
};
//发送消息
for(String severity :routingKeys){
String message = "From "+severity+" routingKey' s message!";
channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());
System.out.println("TopicSend Sent '" + severity + "':'" + message + "'");
}
}catch (Exception e){
e.printStackTrace();
if (connection!=null){
channel.close();
connection.close();
}
}finally {
if (connection!=null){
channel.close();
connection.close();
}
}
}
}

消费者 

 public class ReceiveLogsTopic1 {
private static final String EXCHANGE_NAME = "topic_logs"; public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel(); //声明一个匹配模式的交换机
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
//路由关键字
String[] routingKeys = new String[]{"*.orange.*"};
//绑定路由
for (String routingKey : routingKeys) {
channel.queueBind(queueName, EXCHANGE_NAME, routingKey);
System.out.println("ReceiveLogsTopic1 exchange:" + EXCHANGE_NAME + ", queue:" + queueName + ", BindRoutingKey:" + routingKey);
}
System.out.println("ReceiveLogsTopic1 Waiting for messages"); Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println("ReceiveLogsTopic1 Received '" + envelope.getRoutingKey() + "':'" + message + "'");
}
};
channel.basicConsume(queueName, true, consumer);
}
}
  public class ReceiveLogsTopic2 {
private static final String EXCHANGE_NAME = "topic_logs"; public static void main(String[] argv) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// 声明一个匹配模式的交换器
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
// 路由关键字
String[] routingKeys = new String[]{"*.*.rabbit", "lazy.#"};
// 绑定路由关键字
for (String bindingKey : routingKeys) {
channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
System.out.println("ReceiveLogsTopic2 exchange:"+EXCHANGE_NAME+", queue:"+queueName+", BindRoutingKey:" + bindingKey);
} System.out.println("ReceiveLogsTopic2 Waiting for messages"); Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException {
String message = new String(body, "UTF-8");
System.out.println("ReceiveLogsTopic2 Received '" + envelope.getRoutingKey() + "':'" + message + "'");
}
};
channel.basicConsume(queueName, true, consumer);
}
}

RabbitMQ交换机规则实例的更多相关文章

  1. 初识RabbitMQ,附RabbitMQ+PHP演示实例

    RabbitMQ是一个在AMQP基础上实现的企业级消息系统.何谓消息系统,就是消息队列系统,消息队列是""消费-生产者模型""的一个典型的代表,一端往消息队列中 ...

  2. prometheus linux系统告警规则 实例

    #prometheus linux系统告警规则 实例 #根据实际情况修改参数 #rules.linux.yml groups: - name: linux rules: - alert: Node-D ...

  3. rabbitMQ第三篇:采用不同的交换机规则

    在上一篇我们都是采用发送信息到队列然后队列把信息在发送到消费者,其实实际情况并非如此,rabbitMQ其实真正的思想是生产者不发送任何信息到队列,甚至不知道信息将发送到哪个队列.相反生产者只能发送信息 ...

  4. 认识RabbitMQ交换机模型

    前言 RabbitMQ是消息队列中间件(Message Queue Middleware)中一种,工作虽然有用到,但是却没有形成很好的整体包括,主要是一些基础概念的认识,这里通过阅读<Rabbi ...

  5. 关于RabbitMQ交换机的理解

    RabbitMQ是实现AMQP(高级消息队列协议)的消息中间件的一种,最初起源于金融系统,用于在分布式系统中存储转发消息,在易用性.扩展性.高可用性等方面表现不俗.消息中间件主要用于组件之间的解耦,消 ...

  6. RabbitMQ交换机、RabbitMQ整合springCloud

    目标 1.交换机 2.RabbitMQ整合springCloud 交换机 蓝色区域===生产者 红色区域===Server:又称Broker,接受客户端的连接,实现AMQP实体服务 绿色区域===消费 ...

  7. RabbitMQ交换机

    RabbitMQ中,生产者并不是直接将消息发送给queue,而是先将消息发送给exchange,再由exchange通过不同的路由规则将消息路由到绑定的队列中进行存储,那么为什么要先将消息发送给exc ...

  8. Swift难点-继承中的构造规则实例具体解释

    关于继承中的构造规则是一个难点. 假设有问题,请留言问我. 我的Swift新手教程专栏 http://blog.csdn.net/column/details/swfitexperience.html ...

  9. nginx 正则及rewrite常用规则实例

    一.正则表达式匹配,其中:* ~ 为区分大小写匹配* ~* 为不区分大小写匹配* !~和!~*分别为区分大小写不匹配及不区分大小写不匹配二.文件及目录匹配,其中:* -f和!-f用来判断是否存在文件* ...

随机推荐

  1. x-www-form-urlencoded

    就是application/x-www-from-urlencoded,会将表单内的数据转换为键值对,比如,name=java&age = 23 postman: 2.ajax传值

  2. [转载红鱼儿]Delphi实现微信开发(3)如何使用multipart/form-data格式上传文件

    开始前,先看下要实现的微信接口,上传多媒体文件,这个接口是用Form表单形式上传的文件.对我来说,对http的Form表单一知半解,还好,查到这个资料,如果你也和我一样,必须看看这篇文章. 在xali ...

  3. [GO]删除切片的某个值

    func removePro(ddbenv []*model.EnvInfo, k int) []*model.EnvInfo { :]...) } for k, v := range ddbenv ...

  4. HDU 1718 Rank (排序)

    题意:给你n个学号和成绩,并且给定一个学号,让找这个学号是多少名. 析:用个结构体,按成绩排序,然后找那个学号,这个题有一个小坑,那就是并列的情况, 可能并列多少名,这个要考虑一下,其他的easy! ...

  5. kallinux2.0安装网易云音乐

    安装 dpkg -i netease-cloud-music_1.0.0_amd64.kali2.0(yagami).deb apt-get -f install dpkg -i netease-cl ...

  6. 14)settings.xml

    1. User Level. ${user.home}/.m2/settings.xml 2. Global Level. ${maven.home}/conf/settings.xml <se ...

  7. 解决:无法在发送 HTTP 标头之后进行重定向。 跟踪信息: 在 System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>……

    问题:在MVC的过滤器中验证用户状态时报如下错误:   无法在发送 HTTP 标头之后进行重定向. 跟踪信息:   在 System.Web.HttpResponse.Redirect(String  ...

  8. day16(jdbc进阶,jdbc之dbUtils)

    1.jdbc进阶 jdbc事务管理 jdbc中的事务管理其实就是交给了连接对象去管理.先写一个简单的事务管理 public class Demo01 { private static Connecti ...

  9. 测试与发布(Alpha版本)——小谷围驻广东某工业719电竞大队

    测试与发布(Alpha版本)--小谷围驻广东某工业719电竞大队 一.引言 1.需求规格说明书: https://www.cnblogs.com/TaoTaoLV1/p/9819913.html 2. ...

  10. LoadRunner 技巧之 IP欺骗 (推荐)

    IP欺骗也是也loadrunner自带的一个非常有用的功能. 需要使用ip欺骗的原因:1.当某个IP的访问过于频繁,或者访问量过大是,服务器会拒绝访问请求,这时候通过IP欺骗可以增加访问频率和访问量, ...