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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值