RabbitMQ消息中间件(二):工作模式之简单模式(Hello World)

news/2024/6/16 18:08:45 标签: java-rabbitmq, rabbitmq, java

在下图的模型中,有以下概念:

  • P:生产者,也就是要发送消息的程序。
  • C:消费者,消息的接收者,会一直等待消息到来。
  • queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。

在这里插入图片描述

需求: 使用简单模式完成消息传递

步骤:
(1)创建工程(生成者、消费者),分别添加依赖
(2)编写生产者发送消息
(3)编写消费者接收消息


一、生产者Module

(1)pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>rabbitmq-demo</artifactId>
        <groupId>net.xiaof</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>rabbitmq-producer</artifactId>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--rabbitmq java 客户端-->
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.6.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

(2)生产者类

java">package net.xiaof.producer;

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

/**
 * @author zhangxh
 * @Description: 生产者
 * @date 2020-12-13
 */
public class Producer_HelloWorld {

    public static void main(String[] args) throws Exception {

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

        //3. 创建Channel
        Channel channel = connection.createChannel();

        //4. 声明队列Queue
        /**
         * 【API说明】:
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         * 参数:
         * (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
         * (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
         * (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
         * (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
         * (5)Map<String, Object> arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
         */
        channel.queueDeclare("helloworld_queue", true, false, false, null);

        //5. 发布消息
        /**
         * 【API说明】:
         * basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
         * 参数:
         * (1)String exchange:交换机名称。简单模式下交换机会使用默认的 ""
         * (2)String routingKey:路由名称
         * (3)BasicProperties props:配置信息
         * (4)byte[] body:发送消息数据
         */
        String bodyMsg = "hello rabbitmq~~~好的";
        channel.basicPublish("", "helloworld_queue", null, bodyMsg.getBytes());

        //6. 关闭资源
        channel.close();
        connection.close();

    }

}

二、消费者Module

(1)pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>rabbitmq-demo</artifactId>
        <groupId>net.xiaof</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>rabbitmq-consumer</artifactId>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--rabbitmq java客户端-->
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.6.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

(2)消费者类

java">package net.xiaof.consumer;

import com.rabbitmq.client.*;

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

/**
 * @author zhangxh
 * @Description: 消费者
 * @date 2020-12-13
 */
public class Consumer_HelloWorld {

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

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

        //3. 创建Channel
        Channel channel = connection.createChannel();

        //4. 声明队列Queue
        /**
         * 【API说明】:
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         * 参数:
         * (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
         * (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
         * (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
         * (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
         * (5)Map<String, Object> arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
         */
        channel.queueDeclare("helloworld_queue", true, false, false, null);

        //5. 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             * 回调方法,当收到消息后,会自动执行该方法
             * void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
             * 参数:
             * (1)String consumerTag:标识
             * (2)Envelope envelope:获取一些信息,交换机,路由key...
             * (3)AMQP.BasicProperties properties:配置信息
             * (4)byte[] body:数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                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));
            }
        };
        /**
         * 【API说明】:
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数:
         * (1)String queue:队列名称
         * (2)boolean autoAck:是否自动确认
         * (3)Consumer callback:回调对象
         */
        channel.basicConsume("helloworld_queue", true, consumer);

        //6.关闭资源(消费者需要监听生产者消息,这里不关闭)

    }

}

三、测试

(1)先启动消费者类,消费监听生产者消息。

(2)再启动生产者类生产消息,消费者消息消息,即控制台输出:
在这里插入图片描述



http://www.niftyadmin.cn/n/700690.html

相关文章

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)

Topic类型与Direct相比&#xff0c;都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符&#xff01; Routingkey 一般都是有一个或多个单词组成&#xff0c;多个单词之间以”.”分割&#xff0c;例如&#x…

php在前端的作用,php在前端中的作用

php是一种编译语言&#xff0c;简单来说就是针对我们html构成的页面中的一些变量进行解析&#xff0c;让我们在客户端浏览器上看到正确的内容而不是php的代码。1.php与html的关系 (推荐学习&#xff1a;PHP视频教程)php的作用就是在对包含有php代码的页面中进解析&#xff0c;从…

RabbitMQ消息中间件(四):工作模式之发布订阅模式 (Publish/subscribe)

在 发布订阅模型 中&#xff0c;多了一个exchange角色&#xff0c;而且过程略有变化&#xff1a; P&#xff1a;生产者&#xff0c;也就是要发送消息的程序&#xff0c;但是不再发送到队列中&#xff0c;而是发给X&#xff08;交换机&#xff09;C&#xff1a;消费者&#xff0…

RabbitMQ消息中间件(五):工作模式之路由模式(Routing)

路由模式特点&#xff1a; 队列与交换机的绑定&#xff0c;不能是任意绑定了&#xff0c;而是要指定一个RoutingKey&#xff08;路由key&#xff09;消息的发送方在 向 Exchange发送消息时&#xff0c;也必须指定消息的 RoutingKey。Exchange不再把消息交给每一个绑定的队列&a…

RabbitMQ消息中间件(九):Spring基础框架整合RabbitMQ

一、生产者Module &#xff08;1&#xff09;pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocat…

RabbitMQ消息中间件(十):SpringBoot整合RabbitMQ

一、生产者springboot项目 &#xff08;1&#xff09;pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:sch…

RabbitMQ消息中间件(一):MQ、AMQP、JMS、RabbitMQ基本概念初识

1. 消息中间件概述 MQ全称为Message Queue&#xff0c;消息队列是应用程序和应用程序之间的通信方法。是在消息的传输过程中保存消息的容器。多用于分布式系统之间进行通信。 为什么使用MQ&#xff1f; 在项目中&#xff0c;可将一些无需即时返回且耗时的操作提取出来&#xff…

RabbitMQ高级特性(零):测试项目框架搭建(基于xml配置的spring框架)

一、生产者工程&#xff08;spring-rabbitmq-producers-day02&#xff09; 1.1、pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSch…