【RabbitMQ】04 路由模式

发布时间:2022-07-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【RabbitMQ】04 路由模式脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

【RabbitMQ】04 路由模式

在订阅模式的基础上制定一些特定发送规则

 

创建路由模式的生产者:

注意这些变化,跟之前的订阅模式并不一样

package cn.dzz.routineQueueinPRoducer;

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

import java.nio.charset.StandardCharsets;

public class RoutineInProducer {

    public static void main(String[] args) throws Exception{
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("192.168.2.121");
        connectionFactory.setPort(ConnectionFactory.DEFAULT_amQP_PORT); // 5672
        connectionFactory.setVirtualHost("/dzz"); // 虚拟主机? 默认值 /
        connectionFactory.setUsername("test"); // guest
        connectionFactory.setPassword("123456"); // guest

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        /**
         *  多了一个创建交换机的过程
         *  public DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments) throws IOException {
         *      return this.exchangeDeclare(exchange, type.getType(), durable, autoDelete, internal, arguments);
         *  }
         *  String exchange 交换机名称
         *  String type 交换机类型,这里换成枚举类型,方便查找 com.rabbitmq.client.BuiltinExchangeType
         *      DIRECT("direct"), 定向  简单模式 和 工作模式
         *      fanOUT("fanout"), 扇形  广播(通知给所有和这个交换机绑定的队列)
         *      TOPIC("topic"), 通配符 ?
         *      HEADERS("headers"); 参数匹配, 视频暂不讲解
         *  boolean durable 持久化
         *  boolean autoDelete 自动删除
         *  boolean internal 内部使用 一般false
         *  Map<String, Object> arguments
        */
        String exchangeName = "test_routine";
        channel.exchangeDeclare(
                exchangeName,
                BuiltinExchangeType.DIRECT,
                true,
                false,
                false,
                null
        );

        String queueName1 = "routine - exchange - 1";
        String queueName2 = "routine - exchange - 2";
        channel.queueDeclare(queueName1, true, false, false, null);
        channel.queueDeclare(queueName2, true, false, false, null);

        /**
         * 将交换机和队列绑定
         *  public com.rabbitmq.client.AMQP.Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException {
         *      return this.queueBind(queue, exchange, routingKey, (Map)null);
         *  }
         *  String queue 队列名称
         *  String exchange 交换机名称
         *  String routingKey 路由键,绑定规则
         *      如果是fanout模式, 设置""即可,默认就是给所有队列绑定
         *
         */
        channel.queueBind(queueName1, exchangeName, "error");
        channel.queueBind(queueName2, exchangeName, "info");
        channel.queueBind(queueName2, exchangeName, "warning");
        channel.queueBind(queueName2, exchangeName, "error");

        // 发送消息 这里制定一些不同的消息 以做出区分
        String level = "info";
        for (int i = 0; i < 10; i++) {
            if (i == 4) level = "warning";
            else if (i == 7) level = "error";

            String body = "sending routine msg " + i + level;
            channel.basicPublish(exchangeName, level, null, body.getBytes(StandardCharsets.UTF_8));
        }

        // 释放资
        channel.close();
        connection.close();
    }

}

发送到队列之后可以查看队列面板

【RabbitMQ】04 路由模式

 可以看到队列1 只有3条消息,队列2有10条消息

我们再创建对应的消费者(1 和 2)打印查看

消费和之前的模式一致,只是需要找到对应的队列名称来进行消费

package cn.dzz.routineQueue;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class RoutineQueueInConsumer2 {

    /**
     * 工作队列 消费者
     * @param args
     */
    public static void main(String[] args) throws Exception{
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("192.168.2.121");
        connectionFactory.setPort(ConnectionFactory.DEFAULT_AMQP_PORT); // 5672
        connectionFactory.setVirtualHost("/dzz"); // 虚拟主机? 默认值 /
        connectionFactory.setUsername("test"); // guest
        connectionFactory.setPassword("123456"); // guest

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 声明将不在需要
        // channel.queueDeclare("work_queue", true, false, false, null);

        // 从生产者复制过来需要的队列名称
        String queueName1 = "routine - exchange - 1";
        String queueName2 = "routine - exchange - 2";

        Consumer consumer = new DefaultConsumer(channel) {
            @override
            public void handleDelivery(String consumerTag, envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("body(message) " + new String(body, StandardCharsets.UTF_8));
                System.out.println("- - - - - over - - - - -");
            }
        };

        channel.basicConsume(queueName2, true, consumer);
    }
}

 

消费者1打印

"C:Program Files (x86)Javajdk1.8.0_291binjava.exe" "-javaagent:C:Program FilesJetbrainsIntelliJ IDEA 2021.2.1libidea_rt.jar=60928:C:Program FilesJetBrainsIntelliJ IDEA 2021.2.1bin" -DFile.encoding=UTF-8 -classpath "C:Program Files (x86)Javajdk1.8.0_291jrelibcharsets.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibdeploy.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextaccess-bridge-32.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextcldrdata.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextdnsns.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextjaccess.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextjfxrt.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextlocaledata.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextnashorn.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunec.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunjce_provider.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunmscapi.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunpkcs11.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextzipfs.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjavaws.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjce.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjfr.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjfxswt.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjsse.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibmanagement-agent.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibplugin.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibresources.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibrt.jar;C:UsersAdministratorIdeaProjectsRabbitMQConsumerServicetargetclasses;C:UsersAdministrator.m2repositorycomrabbitmqamqp-client5.6.0amqp-client-5.6.0.jar;C:UsersAdministrator.m2repositoryorgslf4jslf4j-api1.7.25slf4j-api-1.7.25.jar" cn.dzz.routineQueue.RoutineQueueInConsumer1
SLF4J: Failed to load class "org.slf4j.impl.StaticLOGgerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.htML#StaticLoggerBinder for further details.
body(message) sending routine msg 7error
- - - - - over - - - - -
body(message) sending routine msg 8error
- - - - - over - - - - -
body(message) sending routine msg 9error
- - - - - over - - - - -

消费者2打印

"C:Program Files (x86)Javajdk1.8.0_291binjava.exe" "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA 2021.2.1libidea_rt.jar=60918:C:Program FilesJetBrainsIntelliJ IDEA 2021.2.1bin" -Dfile.encoding=UTF-8 -classpath "C:Program Files (x86)Javajdk1.8.0_291jrelibcharsets.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibdeploy.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextaccess-bridge-32.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextcldrdata.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextdnsns.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextjaccess.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextjfxrt.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextlocaledata.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextnashorn.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunec.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunjce_provider.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunmscapi.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextsunpkcs11.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibextzipfs.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjavaws.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjce.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjfr.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjfxswt.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibjsse.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibmanagement-agent.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibplugin.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibresources.jar;C:Program Files (x86)Javajdk1.8.0_291jrelibrt.jar;C:UsersAdministratorIdeaProjectsRabbitMQConsumerServicetargetclasses;C:UsersAdministrator.m2repositorycomrabbitmqamqp-client5.6.0amqp-client-5.6.0.jar;C:UsersAdministrator.m2repositoryorgslf4jslf4j-api1.7.25slf4j-api-1.7.25.jar" cn.dzz.routineQueue.RoutineQueueInConsumer2
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
body(message) sending routine msg 0info
- - - - - over - - - - -
body(message) sending routine msg 1info
- - - - - over - - - - -
body(message) sending routine msg 2info
- - - - - over - - - - -
body(message) sending routine msg 3info
- - - - - over - - - - -
body(message) sending routine msg 4warning
- - - - - over - - - - -
body(message) sending routine msg 5warning
- - - - - over - - - - -
body(message) sending routine msg 6warning
- - - - - over - - - - -
body(message) sending routine msg 7error
- - - - - over - - - - -
body(message) sending routine msg 8error
- - - - - over - - - - -
body(message) sending routine msg 9error
- - - - - over - - - - -

 

脚本宝典总结

以上是脚本宝典为你收集整理的【RabbitMQ】04 路由模式全部内容,希望文章能够帮你解决【RabbitMQ】04 路由模式所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。