RabbitMQ, rabbitmqandroid

Source: Internet
Author: User
Tags rabbitmq

RabbitMQ, rabbitmqandroid

In publish/subscribe mode, the fanout type has a defect, that is, messages that cannot be selectively received.
We can allow the consumer to obtain the specified messages in all published messages.


In the previous example, we bound exchange and queue as follows:

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


Regardless of the exchange type bound to the Code, the null parameter here is the routing key.
The meaning of the routing key is related to the exchange type. For example, if the fanout type is used, the routing key is ignored.


The direct type is used to solve this problem.
Direct exchange is not complex, but the routing key must be corresponding to the exchange pair between the producer and consumer.

 

In the following code, the same exchange and two queues are bound, and the two queues are bound with different binding keys respectively.
(PS: Of course, we can also bind the same routing key to different queues .)
In addition, the SERVERITY variable is the rounting array. Assume that the log is sent through exchange, and the consumer obtains logs of different levels based on their own needs:

final class ChannelFactory_{    private final static ConnectionFactory connFactory = new ConnectionFactory();     public final static String EXCHANGE_NAME = "direct_exchange";    public final static String[] SEVERITY = {"info","warning","error"};     static {        Channel temp = getChannel();        try {            temp.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.DIRECT);        } catch (IOException e) {            e.printStackTrace();        }    }     public static Channel getChannel(int channelNumber){        try {            Connection connection = connFactory.newConnection();            return connection.createChannel(channelNumber);        } catch (IOException e) {            e.printStackTrace();        }return null;    }     public static Channel getChannel(){        try {            Connection connection = connFactory.newConnection();            return connection.createChannel();        } catch (IOException e) {            e.printStackTrace();        }return null;    }     public static void  closeChannel(Channel channel) throws IOException {        channel.close();        channel.getConnection().close();    } }

 

Confirm definition:

 

Consumer only needs the log messages at the warning and error levels (routing:

public static void main(String[] args) throws IOException, InterruptedException {        Channel channel = ChannelFactory_.getChannel();         String queueName = channel.queueDeclare().getQueue();        channel.queueBind(queueName, ChannelFactory_.EXCHANGE_NAME,"warning");        channel.queueBind(queueName, ChannelFactory_.EXCHANGE_NAME,"error");         QueueingConsumer consumer = new QueueingConsumer(channel);        channel.basicConsume(queueName,true,consumer);        while(true){            QueueingConsumer.Delivery delivery = consumer.nextDelivery();            String message = new String(delivery.getBody());            String routingKey = delivery.getEnvelope().getRoutingKey();             System.out.println(" [x] Received '" + routingKey + "':'" + message + "'");        }     }

 

Producer sends logs of all levels:

public static void main(String[] args) throws IOException {        Channel channel = ChannelFactory_.getChannel();        String content = "message "+new Date();         for (int i = 0; i <ChannelFactory_.SEVERITY.length ; i++) {            channel.basicPublish(EXCHANGE_NAME,ChannelFactory_.SEVERITY[i],null,content.getBytes());        }        ChannelFactory_.closeChannel(channel);    }

 

Running result:

 

Direct exchange allows us to selectively accept messages.
However, this is still flawed.
Although I can only require logs at the error and warning levels, I cannot further segment them.
For example, I only want database-related error and warning-level logs.


To achieve this, we need to use another exchange type -- Topic.
When the exchange type is topic, the routing key is a group of words separated by ".", but only 255 bytes.
For example: "stock. usd. nyse", "nyse. vmw", "quick. orange. rabbit"


The difference between topic and direct is that wildcard characters can be used to define the routing key in consumer, for example:
Symbol '*': can match a word.
Symbol '#': can match 0 ~ N words.

 

For example, we use the rounting key to describe an animal.
Format: <character>. <color>. <type>
With the symbol '*', I want to get the animal of the orange ***, that is, "*. orange .*"
With the symbol '#', I want to get a lazy animal, that is, "lazy .#"
If the format is corrupted during use, even if the rounting key is "lazy. orange. male. rabbit", it can match "lazy .#".


Modify the code above to define a topic exchange.

public  final static String EXCHANGE_NAME = "topic_exchange";
temp.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.TOPIC);

 

Confirm definition:

 

Send SQL-related logs:

public static void main(String[] args) throws IOException {        Channel channel = ChannelFactory_.getChannel();        String content = "message #$#$#$#$#$#$";         channel.basicPublish(EXCHANGE_NAME,"warning.sql.connection.close",null,content.getBytes());        channel.basicPublish(EXCHANGE_NAME,"error.sql.syntax",null,content.getBytes());         ChannelFactory_.closeChannel(channel);    }

 

Consumer receives all SQL-related warnings and all errors:

public static void main(String[] args) throws IOException, InterruptedException {        Channel channel = ChannelFactory_.getChannel();         String queueName = channel.queueDeclare().getQueue();        channel.queueBind(queueName, ChannelFactory_.EXCHANGE_NAME,"warning.sql.#");        channel.queueBind(queueName, ChannelFactory_.EXCHANGE_NAME,"error.#");         QueueingConsumer consumer = new QueueingConsumer(channel);        channel.basicConsume(queueName,true,consumer);        while(true){            QueueingConsumer.Delivery delivery = consumer.nextDelivery();            String message = new String(delivery.getBody());            String routingKey = delivery.getEnvelope().getRoutingKey();             System.out.println(" [x] Received '" + routingKey + "':'" + message + "'");        }     }

 

Running result:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.