RabbitMQ实例(三)——使用direct方式,带有Routingkey方式

RabbitMQ实例(三)——使用direct方式,带有Routingkey方式

本文主要介绍的是使用direct方式的Exchange来进行发布和订阅。
direct方式的exchange首先需要制定direct方式,然后需要指定routingkey,最后绑定消费关系,然后开始发布和订阅。下面看一下官方的例子。

发布:
package com.xueyou.demo;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * Created by wuxueyou on 2017/8/20.
 */
public class AppPublishWithRouting {
    private final static String EXCHANGE_NAME = "direct-logs";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.99");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");

        String message = "black message";
        channel.basicPublish(EXCHANGE_NAME, "black", null, message.getBytes());
        System.out.println(message);
        String message2 = "red message";
        channel.basicPublish(EXCHANGE_NAME, "red", null, message2.getBytes());
        System.out.println(message2);
        channel.close();
        connection.close();
    }
}

订阅:
package com.xueyou.demo;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * Created by wuxueyou on 2017/8/20.
 */
public class AppSubScribeWithRouting {
    private final static String EXCHANGE_NAME = "direct-logs";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.99");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        String queueName = channel.queueDeclare().getQueue();

        channel.queueBind(queueName, EXCHANGE_NAME, "black");

        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("receive message :" + message);
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}

这里发布和订阅的时候都需要指定要生产到哪里和要从哪里消费,也就是说routingkey。那么routingkey可以指定多个吗?是可以的。如图:
RabbitMQ实例(三)——使用direct方式,带有Routingkey方式_第1张图片

能够看到,一个channel是可以有多个routingkey的,这样能够灵活的指定发布和订阅消息。
具体的关系,可以看下图:
RabbitMQ实例(三)——使用direct方式,带有Routingkey方式_第2张图片

你可能感兴趣的:(RabbitMQ)