栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 前沿技术 > 大数据 > 大数据系统

RabbitMQ之工作模式

大数据系统 更新时间:发布时间: 百科书网 趣学号
1.RabbitMQ之工作模式简介

RabbitMQ的工作模式指的就是在实际缓存消息过程中实现的流程。

RabbitQM官网提供了六种工作模式:

https://www.rabbitmq.com/getstarted.html

1、Hello Word 简单工作模式
2、Work queues 工作队列模式
3、Publish/Subscribe 发布与订阅模式
4、Routing 路由模式
5、Topics 主题模式
6、RPC 远程调用模式

由于RPC远程调用,不太算 MQ;这里暂不作介绍

2.RabbitMQ工作模式中的相关概念

对于入门RabbitMQ的读者来说,RabbitMQ的相关概念可能晦涩难懂,如果想彻底理解可以结合后面对工作模式的详解中的代码和RabbitMQ 基础架构图来理解。

RabbitMQ 基础架构如下图:
RabbitMQ 中的相关概念:

1、Messag消息,消息是不具体的,它由消息头和消息体组成。消息体是不透明的,而消息头则由一系列的可选属性组成,这些属性包括routing-key(路由键)、priority(相对于其他消息的优先权)、delivery-mode(指出该消息可能需要持久性存储)等。

2、Publisher 消息的生产者,也是一个向交换器发布消息的客户端应用程序。

3、Exchang交换器,用来接收生产者发送的消息并将这些消息路由给服务器中的队列。

4、Bindin绑定,用于消息队列和交换器之间的关联。一个绑定就是基于路由键将交换器和消息队列连接起来的路由规则,所以可以将交换器理解成一个由绑定构成的路由表。

5、Queu消息队列,用来保存消息直到发送给消费者。它是消息的容器,也是消息的终点。一个消息可投入一个或多个队列。消息一直在队列里面,等待消费者连接到这个队列将其取走。

6、Connection 网络连接,比如一个TCP连接。

7、Channe 信道,多路复用连接中的一条独立的双向数据流通道。信道是建立在真实的TCP连接内地虚拟连接,AMQP命令都是通过信道发出去的,不管是发布消息、订阅队列还是接收消息,这些动作都是通过信道完成。因为对于操作系统来说建立和销毁 TC都是非常昂贵的开销,所以引入了信道的概念,以复用一条 TCP 连接。

8、Consume 消息的消费者,表示一个从消息队列中取得消息的客户端应用程序。

9、Virtual Ho虚拟主机,表示一批交换器、消息队列和相关对象。虚拟主机是共享相同的身份认证和加密环境的独立服务器域。每个 vhost 本质上就是一min版的 RabbitMQ 服务器,拥有自己的队列、交换器、绑定和权限机制。vhost 是 AMQ概念的基础,必须在连接时指定,RabbitM 默认的 vhost 是 / 。

10、Broker 表示消息队列服务器实体

介绍完基础概念,下面上代码,让我们根据代码更加深入的理解RabbitMQ的工作模式

Hello Word 简单工作模式

1.在相关文件夹下面新建两个Maven项目(消费者和生产者)

producr:生产者,相当于发送消息的一方
consumer:消费者,相当于接收消息的一方

2.在pom.xml中导入spring集成RabbitMQ的jar

    
        
            com.rabbitmq
            amqp-client
            5.6.0
        
    

3.编写producer端代码发送消息

在producre项目下的com.xxx.rabbitMQ包下建立 Producer_HelloWorld 类

public class Producer_HelloWorld {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("RubbitMQ安装的主机ip地址");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
        //5. 创建队列Queue
        
        //如果没有一个名字叫hello_world的队列,则会创建该队列,如果有则不会创建
        channel.queueDeclare("hello_world",true,false,false,null);
        
        String body = "hello rabbitmq~~~";
        //6. 发送消息
        channel.basicPublish("","hello_world",null,body.getBytes());
        //7.释放资源
      channel.close();
      connection.close();

    }
}

4.编consumer端代码发送消息
consumer项目下的com.xxx.rabbitMQ包下建立Consumerr_HelloWorld 类

public class Consumer_HelloWorld {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
        //5. 创建队列Queue
        
        //如果没有一个名字叫hello_world的队列,则会创建该队列,如果有则不会创建
        channel.queueDeclare("hello_world",true,false,false,null);
        
        // 接收消息    匿名内部类
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag:"+consumerTag);
                System.out.println("Exchange:"+envelope.getExchange());
                System.out.println("RoutingKey:"+envelope.getRoutingKey());
                System.out.println("properties:"+properties);
                System.out.println("body:"+new String(body));
            }
        };
        //接收消息
        channel.basicConsume("hello_world",true,consumer);
        //关闭资源?不要
    }
}

5.启动服务观察打印结果

启动自己安装的RibbitMQ服务,再分别运行Producre和Consumer的相关类发送和接收消息,在RibbiMQ的管理界面就可以看到相应的服务和idea控制台打印的消息

Work queues 工作队列模式

work queres不用自动声明交换机,但是它会调用默认的交换机,该工作模式采用的是在生产者端创建多个队列queue,然后生产者端将消息品军储存在每个队列中。来到消费者端,消费者端通过创建connection连接,然后绑定生产者创建的队列,接收相应队列中的消息。
⚫ Work Queues:与入门程序的简单模式相比,多了一个或一些消费端,多个消费端共同消费同一个队列中的消息。
⚫ 应用场景:对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。

1.在相关文件夹下面新建两个Maven项目(消费者和生产者)

producr:生产者,相当于发送消息的一方
consumer:消费者,相当于接收消息的一方

2.在pom.xml中导入spring集成RabbitMQ的jar

    
        
            com.rabbitmq
            amqp-client
            5.6.0
        
    

3.编写producer端代码发送消息

在producre项目下的com.xxx.rabbitMQ包下建立 Producer_WorkQueues 类


public class Producer_WorkQueues {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
        //5. 创建队列Queue
        
        //如果没有一个名字叫hello_world的队列,则会创建该队列,如果有则不会创建
        channel.queueDeclare("work_queues",true,false,false,null);
        
        for (int i = 1; i <= 10; i++) {
            String body = i+"hello rabbitmq~~~";
            //6. 发送消息
            channel.basicPublish("","work_queues",null,body.getBytes());
        }
        //7.释放资源
      channel.close();
      connection.close();

    }
}

4.编consumer端代码发送消息
consumer项目下的com.xxx.rabbitMQ包下建立Consumer_WorkQueues1 类和Consumer_WorkQueues2类

public class Consumer_WorkQueues1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
        //5. 创建队列Queue
        
        //如果没有一个名字叫hello_world的队列,则会创建该队列,如果有则不会创建
        channel.queueDeclare("work_queues",true,false,false,null);
        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
            }
        };
        channel.basicConsume("work_queues",true,consumer);
        //关闭资源?不要

    }
}



public class Consumer_WorkQueues2 {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
        //5. 创建队列Queue
        
        //如果没有一个名字叫hello_world的队列,则会创建该队列,如果有则不会创建
        channel.queueDeclare("work_queues",true,false,false,null);

        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
            }
        };
        channel.basicConsume("work_queues",true,consumer);
        //关闭资源?不要
    }
}


5.启动服务观察打印结果

启动自己安装的RibbitMQ服务,再分别运行Producre和Consumer的相关类发送和接收消息,在RibbiMQ的管理界面就可以看到相应的服务和idea控制台打印的消息

Publish/Subscribe 发布与订阅模式

发布和订阅工作模式需要自己手动的创建交换机,但是交换又有四种不同的类型,分别

DIRECT(“direct”):定向,将消息发送到指定队列
FANOUT(“fanout”):广播,将消息发送到每个队列
TOPIC(“topic”):通配符的方式,将消息发送到匹配队列
HEADERS(“headers”):参数匹配

因为前三个交换机比较常用,这里就介绍前三个类型的交换机。

由于发布和订阅模式对应的交换机类型式FANOUT广播模式,所以在声明交换机的时候,需要将交换机定义为FANOUT类型。
发布与订阅模式实际上是通过交换机的FANOUT模式,将需要发送的消息,装到每个队列中,所以每个队列都发送消息的全部,每个队列的消息都是相同的,不像work queues工作队列模式,是分别将信息分发到队列中,所有队列中的消息组合起来才是全部的消息,然后消费端通过创建connection绑定对应的队列queue,介绍该队列中的全部消息。

1.在相关文件夹下面新建两个Maven项目(消费者和生产者)

producr:生产者,相当于发送消息的一方
consumer:消费者,相当于接收消息的一方

2.在pom.xml中导入spring集成RabbitMQ的jar

    
        
            com.rabbitmq
            amqp-client
            5.6.0
        
    

3.编写producer端代码发送消息

在producre项目下的com.xxx.rabbitMQ包下建立 Producer_PubSub 类



public class Producer_PubSub {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
       
       String exchangeName = "test_fanout";
        //5. 创建交换机
        channel.exchangeDeclare(exchangeName,BuiltinExchangeType.FANOUT,true,false,false,null);
        //6. 创建队列
        String queue1Name = "test_fanout_queue1";
        String queue2Name = "test_fanout_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);
        //7. 绑定队列和交换机
        
        channel.queueBind(queue1Name,exchangeName,"");
        channel.queueBind(queue2Name,exchangeName,"");

        String body = "日志信息:张三调用了findAll方法...日志级别:info...";
        //8. 发送消息
        channel.basicPublish(exchangeName,"",null,body.getBytes());

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


4.编consumer端代码发送消息
consumer项目下的com.xxx.rabbitMQ包下建立Consumer_PubSub1 类和Consumer_PubSub2类

public class Consumer_PubSub1 {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
        String queue1Name = "test_fanout_queue1";
        String queue2Name = "test_fanout_queue2";
        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
                System.out.println("将日志信息打印到控制台.....");
            }
        };
        channel.basicConsume(queue1Name,true,consumer);
        //关闭资源?不要
    }
}


public class Consumer_PubSub2 {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();


        String queue1Name = "test_fanout_queue1";
        String queue2Name = "test_fanout_queue2";


        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
                System.out.println("将日志信息保存数据库.....");
            }
        };
        channel.basicConsume(queue2Name,true,consumer);


        //关闭资源?不要

    }
}

5.启动服务观察打印结果

启动自己安装的RibbitMQ服务,再分别运行Producre和Consumer的相关类发送和接收消息,在RibbiMQ的管理界面就可以看到相应的服务和idea控制台打印的消息

Routing 路由模式

⚫ 队列与交换机的绑定,不能是任意绑定了,而是要指定一个 RoutingKey(路由key)
⚫ 消息的发送方在向 Exchange 发送消息时,也必须指定消息的 RoutingKey
⚫ Exchange 不再把消息交给每一个绑定的队列,而是根据消息的 Routing Key 进行判断,只有队列的
Routingkey 与消息的 Routing key 完全一致,才会接收到消息

⚫ P:生产者,向 Exchange 发送消息,发送消息时,会指定一个routing key
⚫ X:Exchange(交换机),接收生产者的消息,然后把消息递交给与 routing key 完全匹配的队列
⚫ C1:消费者,其所在队列指定了需要 routing key 为 error 的消息
⚫ C2:消费者,其所在队列指定了需要 routing key 为 info、error、warning 的消息

Routing 路由模式其实就是通过将交换机设置为DIRECT模式,然后在创建队列queue的时候给每个队列设置一个routing key ,然后给发送的每条消息也设置一个routing key ,只有当发送消息的生产者发送的消息中的routing key和队列中设置的routing key相同的时候,这条消息才能放入指定的队列中。

1.在相关文件夹下面新建两个Maven项目(消费者和生产者)

producr:生产者,相当于发送消息的一方
consumer:消费者,相当于接收消息的一方

2.在pom.xml中导入spring集成RabbitMQ的jar

    
        
            com.rabbitmq
            amqp-client
            5.6.0
        
    

3.编写producer端代码发送消息

在producre项目下的com.xxx.rabbitMQ包下建立 Producer_Routing 类



public class Producer_Routing {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
       

       String exchangeName = "test_direct";
        //5. 创建交换机
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,false,null);
        //6. 创建队列
        String queue1Name = "test_direct_queue1";
        String queue2Name = "test_direct_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);
        //7. 绑定队列和交换机
        
        //队列1绑定 error
        channel.queueBind(queue1Name,exchangeName,"error");
        //队列2绑定 info  error  warning
        channel.queueBind(queue2Name,exchangeName,"info");
        channel.queueBind(queue2Name,exchangeName,"error");
        channel.queueBind(queue2Name,exchangeName,"warning");

        String body = "日志信息:张三调用了delete方法...出错误了。。。日志级别:error...";
        //8. 发送消息
            
        //下面代码表示,这条信息会被发送到routingKey的队列中,其他不是该warning的routingKey的队列不会接收到该消息
        channel.basicPublish(exchangeName,"warning",null,body.getBytes());

        //9. 释放资源
        channel.close();
        connection.close();

    }
}


4.编consumer端代码发送消息
consumer项目下的com.xxx.rabbitMQ包下建立Consumer_Routing1 类和Consumer_Routing2类

public class Consumer_Routing1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
        String queue1Name = "test_direct_queue1";
        String queue2Name = "test_direct_queue2";
        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
                System.out.println("将日志信息打印到控制台.....");
            }
        };
        channel.basicConsume(queue2Name,true,consumer);
        //关闭资源?不要
    }
}



public class Consumer_Routing2 {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();


        String queue1Name = "test_direct_queue1";
        String queue2Name = "test_direct_queue2";


        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
                System.out.println("将日志信息存储到数据库.....");
            }
        };
        channel.basicConsume(queue1Name,true,consumer);


        //关闭资源?不要

    }
}

5.启动服务观察打印结果

启动自己安装的RibbitMQ服务,再分别运行Producre和Consumer的相关类发送和接收消息,在RibbiMQ的管理界面就可以看到相应的服务和idea控制台打印的消息

Topics 主题模式

⚫ Topic 类型与 Direct 相比,都是可以根据 RoutingKey 把消息路由到不同的队列。只不过 Topic 类Exchange 可以让队列在绑定 Routing key 的时候使用通配符!
⚫ Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: xiaoyang.insert
⚫ 通配符规则:# 匹配一个或多个词,* 匹配不多不少恰好1个词,例如xioayang.# 能够匹配 xiaoyang.insert.abc
或者 xiaoyang.insert,xiaoyang.但是* 只能匹配 xiaoyang.insert

1.在相关文件夹下面新建两个Maven项目(消费者和生产者)

producr:生产者,相当于发送消息的一方
consumer:消费者,相当于接收消息的一方

2.在pom.xml中导入spring集成RabbitMQ的jar

    
        
            com.rabbitmq
            amqp-client
            5.6.0
        
    

3.编写producer端代码发送消息

在producre项目下的com.xxx.rabbitMQ包下建立 Producer_Topics 类



**
 * 发送消息
 */
public class Producer_Topics {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();
       

       String exchangeName = "test_topic";
        //5. 创建交换机
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC,true,false,false,null);
        //6. 创建队列
        String queue1Name = "test_topic_queue1";
        String queue2Name = "test_topic_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);
        //7. 绑定队列和交换机
        

        // routing key  系统的名称.日志的级别。
        //=需求: 所有error级别的日志存入数据库,所有order系统的日志存入数据库
        channel.queueBind(queue1Name,exchangeName,"#.error");
        channel.queueBind(queue1Name,exchangeName,"order.*");
        channel.queueBind(queue2Name,exchangeName,"*.*");

        String body = "日志信息:张三调用了findAll方法...日志级别:info...";
        //8. 发送消息
        channel.basicPublish(exchangeName,"goods.error",null,body.getBytes());

        //9. 释放资源
        channel.close();
        connection.close();

    }
}


4.编consumer端代码发送消息
consumer项目下的com.xxx.rabbitMQ包下建立Consumer_Topic1 类和Consumer_Topic2类

public class Consumer_Topic1 {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();


        String queue1Name = "test_topic_queue1";
        String queue2Name = "test_topic_queue2";


        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
                System.out.println("将日志信息存入数据库.......");
            }
        };
        channel.basicConsume(queue1Name,true,consumer);


        //关闭资源?不要

    }
}


public class Consumer_Topic2 {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("192.168.43.137");//ip  默认值 localhost
        factory.setPort(5672); //端口  默认值 5672
        factory.setVirtualHost("/");//虚拟机 默认值/
        factory.setUsername("guest");//用户名 默认 guest
        factory.setPassword("guest");//密码 默认值 guest
        //3. 创建连接 Connection
        Connection connection = factory.newConnection();
        //4. 创建Channel
        Channel channel = connection.createChannel();


        String queue1Name = "test_topic_queue1";
        String queue2Name = "test_topic_queue2";


        
        // 接收消息
        Consumer consumer = new DefaultConsumer(channel){
            
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              
                System.out.println("body:"+new String(body));
                System.out.println("将日志信息打印控制台.......");
            }
        };
        channel.basicConsume(queue2Name,true,consumer);


        //关闭资源?不要

    }
}

5.启动服务观察打印结果

启动自己安装的RibbitMQ服务,再分别运行Producre和Consumer的相关类发送和接收消息,在RibbiMQ的管理界面就可以看到相应的服务和idea控制台打印的消息

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/279822.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号