RabbitMQ 四种Exchange
AMQP协议中的核心思想就是生产者和消费者隔离,生产者从不直接将消息发送给队列。生产者通常不知道是否一个消息会被发送到队列中,只是将消息发送到一个交换机。先由Exchange来接收,然后Exchange按照特定的策略转发到Queue进行存储。同理,消费者也是如此。Exchange 就类似于一个交换机,转发各个消息分发到相应的队列中。
RabbitMQ提供了四种Exchange模式:fanout、direct、topic、header 。 header模式在实际使用中较少。
Direct Exchange – 处理路由键。需要将一个队列绑定到交换机上,要求该消息与一个特定的路由键完全匹配。这是一个完整的匹配。如果一个队列绑定到该交换机上要求路由键 “dog”,则只有被标记为“dog”的消息才被转发,不会转发dog.puppy,也不会转发dog.guard,只会转发dog。
- Channel channel = connection.createChannel();
- channel.exchangeDeclare("exchangeName", "direct"); //direct fanout topic
- channel.queueDeclare("queueName");
- channel.queueBind("queueName", "exchangeName", "routingKey");
- byte[] messageBodyBytes = "hello world".getBytes();
- //需要绑定路由键
- channel.basicPublish("exchangeName", "routingKey", MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
Fanout Exchange – 不处理路由键。你只需要简单的将队列绑定到交换机上。一个发送到交换机的消息都会被转发到与该交换机绑定的所有队列上。很像子网广播,每台子网内的主机都获得了一份复制的消息。Fanout交换机转发消息是最快的。
- Channel channel = connection.createChannel();
- channel.exchangeDeclare("exchangeName", "fanout"); //direct fanout topic
- channel.queueDeclare("queueName");
- channel.queueBind("queueName", "exchangeName", "routingKey");
- channel.queueDeclare("queueName1");
- channel.queueBind("queueName1", "exchangeName", "routingKey1");
- byte[] messageBodyBytes = "hello world".getBytes();
- //路由键需要设置为空
- channel.basicPublish("exchangeName", "", MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
Topic Exchange – 将路由键和某模式进行匹配。此时队列需要绑定要一个模式上。符号“#”匹配一个或多个词,符号“*”匹配不多不少一个词。因此“audit.#”能够匹配到“audit.irs.corporate”,但是“audit.*” 只会匹配到“audit.irs”。我在RedHat的朋友做了一张不错的图,来表明topic交换机是如何工作的:
- Channel channel = connection.createChannel();
- channel.exchangeDeclare("exchangeName", "topic"); //direct fanout topic
- channel.queueDeclare("queueName");
- channel.queueBind("queueName", "exchangeName", "routingKey.*");
- byte[] messageBodyBytes = "hello world".getBytes();
- channel.basicPublish("exchangeName", "routingKey.one", MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
header exchange:
Headers类型的exchange使用的比较少,它也是忽略routingKey的一种路由方式。是使用Headers来匹配的。Headers是一个键值对,可以定义成Hashtable。发送者在发送的时候定义一些键值对,接收者也可以再绑定时候传入一些键值对,两者匹配的话,则对应的队列就可以收到消息。匹配有两种方式all和any。这两种方式是在接收端必须要用键值"x-mactch"来定义。all代表定义的多个键值对都要满足,而any则代码只要满足一个就可以了。fanout,direct,topic exchange的routingKey都需要要字符串形式的,而headers exchange则没有这个要求,因为键值对的值可以是任何类型。
1.生产者Producer.Java
- package cn.slimsmart.rabbitmq.demo.headers;
- import java.util.Date;
- import java.util.Hashtable;
- import java.util.Map;
- import org.springframework.amqp.core.ExchangeTypes;
- import com.rabbitmq.client.AMQP;
- import com.rabbitmq.client.AMQP.BasicProperties;
- import com.rabbitmq.client.AMQP.BasicProperties.Builder;
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.ConnectionFactory;
- public class Producer {
- private final static String EXCHANGE_NAME = "header-exchange";
- @SuppressWarnings("deprecation")
- public static void main(String[] args) throws Exception {
- // 创建连接和频道
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost("192.168.36.102");
- // 指定用户 密码
- factory.setUsername("admin");
- factory.setPassword("admin");
- // 指定端口
- factory.setPort(AMQP.PROTOCOL.PORT);
- Connection connection = factory.newConnection();
- Channel channel = connection.createChannel();
- //声明转发器和类型headers
- channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.HEADERS,false,true,null);
- String message = new Date().toLocaleString() + " : log something";
- Map<String,Object> headers = new Hashtable<String, Object>();
- headers.put("aaa", "01234");
- Builder properties = new BasicProperties.Builder();
- properties.headers(headers);
- // 指定消息发送到的转发器,绑定键值对headers键值对
- channel.basicPublish(EXCHANGE_NAME, "",properties.build(),message.getBytes());
- System.out.println("Sent message :'" + message + "'");
- channel.close();
- connection.close();
- }
- }
2.消费者Consumer.java
- package cn.slimsmart.rabbitmq.demo.headers;
- import java.util.Hashtable;
- import java.util.Map;
- import org.springframework.amqp.core.ExchangeTypes;
- import com.rabbitmq.client.AMQP;
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.ConnectionFactory;
- import com.rabbitmq.client.QueueingConsumer;
- public class Consumer {
- private final static String EXCHANGE_NAME = "header-exchange";
- private final static String QUEUE_NAME = "header-queue";
- public static void main(String[] args) throws Exception {
- // 创建连接和频道
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost("192.168.36.102");
- // 指定用户 密码
- factory.setUsername("admin");
- factory.setPassword("admin");
- // 指定端口
- factory.setPort(AMQP.PROTOCOL.PORT);
- Connection connection = factory.newConnection();
- Channel channel = connection.createChannel();
- //声明转发器和类型headers
- channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.HEADERS,false,true,null);
- channel.queueDeclare(QUEUE_NAME,false, false, true,null);
- Map<String, Object> headers = new Hashtable<String, Object>();
- headers.put("x-match", "any");//all any
- headers.put("aaa", "01234");
- headers.put("bbb", "56789");
- // 为转发器指定队列,设置binding 绑定header键值对
- channel.queueBind(QUEUE_NAME, EXCHANGE_NAME,"", headers);
- QueueingConsumer consumer = new QueueingConsumer(channel);
- // 指定接收者,第二个参数为自动应答,无需手动应答
- channel.basicConsume(QUEUE_NAME, true, consumer);
- while (true) {
- QueueingConsumer.Delivery delivery = consumer.nextDelivery();
- String message = new String(delivery.getBody());
- System.out.println(message);
- }
- }
- }