Springboot integrate RabbitMQ (IV): Route (Routing)

In this article, we will achieve another function - subscribe only part of the message. For example, we just need a serious error log information written to the log file (saved to disk), but still all the log information output to the console architecture plus understand springcloud beg: 353,624,725 nine
bindings (binding)
in the previous example, we have created a bind. Tut3Config can recall in our files about this code:

@Bean
public Binding binding1(FanoutExchange fanout, Queue autoDeleteQueue1) {
    return BindingBuilder.bind(autoDeleteQueue1).to(fanout);
}

Binding (Binding) refers to the relationship exchanger (Exchange) and a queue (Queue) a. It can be simply understood as: interested in this exchanger (Exchange) a message queue (queue).
Binding can use an additional parameter routingKey. We exchanger and passed to the queue BindingBuilder, and routingKey bind to the switch, as shown below:

@Bean
public Binding binding1a(DirectExchange direct, Queue autoDeleteQueue1) {
    return BindingBuilder.bind(autoDeleteQueue1)
        .to(direct)
        .with("orange");
}

routingKey meaning depends on the type of exchange. For example, fanout exchange we previously used, ignores its value.

Direct exchange
our system logs all messages broadcast to all consumers (consumers). We intend to expand it to make it based on the severity of the log message filtering. For example, we might just want to more serious errors (error) log is written to disk, to avoid wasting disk space on the warning (warning) or information (info) log.

fanout exchange we use do not have enough flexibility - it can do is just radio.

We will use direct exchange instead. The routing algorithm is very simple - will switch to the key bindings (binding key) key and routing (routing key) an exact match, thereby determining that the message queue to which the distribution.
A good description of this scenario of FIG:
Here Insert Picture Description

In this scenario, we can see the direct exchange X and two queues were binding. The first queue orange used as the binding key, the second queue has two binding black used as a binding key, a further use of green.

This way, when the routing key is published to the message orange exchanger, will be routed to the queue Q1. Routing keys as green or black message will be routed to Q2. All other messages will be discarded.

A plurality of bindings (Multiple bindings)
Here Insert Picture Description
a plurality of queues using the same key bindings are possible. In this example, we can add a binding between X and Q1, use the black key bindings. As a result, direct exchange and fanout exchange on the behavior of the same, the message will be broadcast to all matching queue. Routing message with black keys simultaneously sent to Q1 and Q2.

Announced that
we will use more than this model as our routing system to send a message to the direct exchange rather than a fanout exchange. We will use color as a key routes, so consumers will be able to choose the color you want to receive (or subscription) corresponding to the message to the consumer.

We started to do some Spring configuration Tut4Config, the need to create a switch

@Bean
public DirectExchange direct() {
    return new DirectExchange("tut.direct");
}

Receive messages with the same way on a tutorial, but there are some differences - we need to create a new binding for each color of interest.
Learn springcloud architecture can be added to beg: 3536247259

@Bean
public Binding binding1a(DirectExchange direct, Queue autoDeleteQueue1) {
    return BindingBuilder.bind(autoDeleteQueue1)
        .to(direct)
        .with("orange");

Code integrated
Here Insert Picture Description
producers

public class Tut4Sender {

   @Autowird 
    private AmqpTemplate template;

    @Autowird
    private DirectExchange direct;

    private int index;

    private int count;

    private final String[] keys = {"orange", "black", "green"};

    @Scheduled(fixedDelay = 1000, initialDelay = 500)
    public void send() {
        StringBuilder builder = new StringBuilder("Hello to ");
        if (++this.index == 3) {
            this.index = 0;
        }
        String key = keys[this.index];
        builder.append(key).append(' ').append(Integer.toString(++this.count));
        String message = builder.toString();
        template.convertAndSend(direct.getName(), key, message);
        System.out.println(" [x] Sent '" + message + "'");
    }

}

consumer

public class Tut4Receiver {

    @RabbitListener(queues = "#{autoDeleteQueue1.name}")
    public void receiver1(String in) throws InterruptedException {
        receiver(in, 1);
    }

    @RabbitListener(queues = "#{autoDeleteQueue2.name}")
    public void receiver2(String in) throws InterruptedException {
        receiver(in, 2);
    }

    private void receiver(String in, int instance) throws InterruptedException {
        StopWatch watch = new StopWatch();
        watch.start();
        System.out.println("instance " + instance + " [x] Received '" + in + "'");
        doWork(in);
        watch.stop();
        System.out.println("instance " + instance + " [x] Done in " +
                watch.getTotalTimeSeconds() + "s");
    }

    private void doWork(String in) throws InterruptedException {
        for (char ch : in.toCharArray()) {
            if (ch == '.') {
                Thread.sleep(1000);
            }
        }
    }

}

Configuration class

Profile({"tut4", "routing"})
@Configuration
public class Tut4Config {


    @Bean
    public DirectExchange direct() {
        return new DirectExchange("tut.direct");
    }

   @Profile ("receiver")
    private static class ReceiverConfig {

        @Bean
        public Queue autoDeleteQueue1() {
            return new AnonymousQueue();
        }

        @Bean
        public Queue autoDeleteQueue2() {
            return new AnonymousQueue();
        }

        @Bean
        public Binding binding1a(DirectExchange direct, Queue autoDeleteQueue1) {
            return BindingBuilder.bind(autoDeleteQueue1)
                    .to(direct)
                    .with("orange");
        }

        @Bean
        public Binding binding1b(DirectExchange direct, Queue autoDeleteQueue1) {
            return BindingBuilder.bind(autoDeleteQueue1)
                    .to(direct)
                    .with("black");
        }

        @Bean
        public Binding binding2a(DirectExchange direct, Queue autoDeleteQueue2) {
            return BindingBuilder.bind(autoDeleteQueue2)
                    .to(direct)
                    .with("green");
        }

        @Bean
        public Binding binding2b(DirectExchange direct, Queue autoDeleteQueue2) {
            return BindingBuilder.bind(autoDeleteQueue2)
                    .to(direct)
                    .with("black");
        }

       @Bean 
        public Tut4Receiver receiver() {
            return new Tut4Receiver();
        }

    }
Profile("sender")
    @Bean
    public Tut4Sender sender() {
        return new Tut4Sender();
    }

}

Run
maven compiler

mvn clean package -Dmaven.test.skip=true
运行

java -jar target/rabbitmq-tutorial-0.0.1-SNAPSHOT.jar --spring.profiles.active=tut4,receiver --tutorial.client.duration=60000
java -jar target/rabbitmq-tutorial-0.0.1-SNAPSHOT.jar --spring.profiles.active=tut4,sender --tutorial.client.duration=60000
输出

// Sender
Ready … running for 60000ms
[x] Sent ‘Hello to black 1’
[x] Sent ‘Hello to green 2’
[x] Sent ‘Hello to orange 3’
[x] Sent ‘Hello to black 4’

// Receiver
Ready … running for 60000ms
instance 2 [x] Received ‘Hello to black 1’
instance 1 [x] Received ‘Hello to black 1’
instance 2 [x] Done in 0.0s
instance 1 [x] Done in 0.0s
instance 2 [x] Received ‘Hello to green 2’
instance 2 [x] Done in 0.0s
instance 1 [x] Received ‘Hello to orange 3’
instance 1 [x] Done in 0.0s
instance 1 [x] Received ‘Hello to black 4’
instance 1 [x] Done in 0.0s
instance 2 [x] Received ‘Hello to black 4’
instance 2 [x] Done in 0.0s

Published 103 original articles · won praise 116 · Views 6116

Guess you like

Origin blog.csdn.net/weixin_45821812/article/details/104690481