RabbitMQ-Java实现Routing路由模式 - Go语言中文社区

RabbitMQ-Java实现Routing路由模式


路由模式

队列需要有一个routingKey与交换机exchange相匹配,此时交换机的type为direct

 

 

适用情景举例:对于error的情况需要发送到两个队列,而 info 或是 warning 情况只需要发送到一个队列,可以通过把key设置为 error实现路由。

新建连接RabbitMQ的工具类utils

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
 
import java.io.IOException;
import java.util.concurrent.TimeoutException;
 
public class utils {
    public  static Connection getConnection() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setVirtualHost("/vhost_zdy");
        factory.setUsername("username");
        factory.setPassword("password");
 
        return factory.newConnection();
    }
}

新建生产者类RoutingSend,分别发送key为error info waring的消息各三条

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

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RoutingSend {
    private final static String EXCHANGE_NAME = "Routing_exchange";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = utils.getConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME,"direct");
        //声明key
        //String routingKey="error";
        //String routingKey="info";
        String routingKey="warning";

        for(int i=0;i<3;i++)//发3条消息
        {
            String msg="msg"+":"+routingKey+i;
            channel.basicPublish(EXCHANGE_NAME, routingKey, null, msg.getBytes());
            Thread.sleep(20);//假设每20ms发送一次消息
            System.out.println("send:"+ msg);
        }

        channel.close();
        connection.close();

    }
}

 

新建消费者RoutingReceive_1 ——只接受key为error

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RoutingReceive_1 {
    private final static String QUEUE_NAME = "Routing_queue_error";
    private final static String EXCHANGE_NAME = "Routing_exchange";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = utils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"error");
        channel.basicQos(1);//保证一次只分发一个n" +
        System.out.println(" [1] Waiting for messages.");

        DefaultConsumer defaultConsumer= new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"UTF-8");
                System.out.println("[1]receive:"+ msg);
                try {
                    Thread.sleep(2000);//假设消费者1处理时间为2s
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("[1]done:"+ msg);
                    //手动回执
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoack=false;
        channel.basicConsume(QUEUE_NAME,autoack,defaultConsumer);
    }
}

新建消费者RoutingReceive_2——接受error,info,waring消息

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RoutingReceive_2 {
    private final static String QUEUE_NAME = "Routing_queue_all";
    private final static String EXCHANGE_NAME = "Routing_exchange";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = utils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //绑定多个key
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"error");
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"info");
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"warning");
        channel.basicQos(1);//保证一次只分发一个n" +
        System.out.println(" [2] Waiting for messages.");

        DefaultConsumer defaultConsumer= new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"UTF-8");
                System.out.println("[2]receive:"+ msg);
                try {
                    Thread.sleep(1000);//假设消费者2处理时间为1s
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("[2]done:"+ msg);
                    //手动回执
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoack=false;
        channel.basicConsume(QUEUE_NAME,autoack,defaultConsumer);
    }
}

 

消费者1只接受到error的消息

消费者2接受到error,info,warning的消息

更多详情请参考官方文档

https://www.rabbitmq.com/tutorials/tutorial-four-java.html

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_38905818/article/details/104158722
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 22:28:56
  • 阅读 ( 1172 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢