RabbitMQ 之 Hello World

一、概述

RabbitMQ 有很多的使用模式,具体的可以去参考官网,本次我们将简单的搭建一个 Hello World,该模式下只有一个 Producer(生产者)、一个队列(Queue)、一个消费者(Consumer)

二、RabbitMQ 核心工作原理

三、引入对应的依赖

<dependencies>
    <!--RabbitMQ 依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!--RabbitMQ 测试依赖-->
    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>8</source>
                <target>8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

四、生产者

@Slf4j
public class Producer {
    private static final String QUEUE_NAME = "helloWorld";
    private static final String HOST_ADDRESS = "192.168.59.135";
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin123";

    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置主机地址、用户名、密码
        factory.setHost(HOST_ADDRESS);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        // 使用连接工厂创建连接对象
        Connection connection = factory.newConnection();
        // 使用连接对象创建信道
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, true, null);

        // 定义要发送的消息
        String message = "xiaomaomao";
        /**
         * 发送消息
         * 参数一、交换机名称,如果使用空字符串("")则代表使用默认交换机
         * 参数二、队列名称
         * 参数三、消息的类型(是否持久化、优先级)
         * 参数四、真正要发送的消息内容(二进制形式)
         */
        for (int i = 1; i < 11; i++) {
            channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_BASIC, message.getBytes(StandardCharsets.UTF_8));
        }

        log.info("producer send message successfully");
    }
}

五、消费者

@Slf4j
public class Consumer {
    private static final String QUEUE_NAME = "helloWorld";
    private static final String HOST_ADDRESS = "192.168.59.135";
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin123";

    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置主机地址、用户名、密码
        factory.setHost(HOST_ADDRESS);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        // 连接工厂创建连接对象
        Connection connection = factory.newConnection();
        // 连接对象创建信道
        Channel channel = connection.createChannel();

        /**
         * 声明队列
         * 参数一、队列名称
         * 参数二、队列是否持久化
         * 参数三、是否是排它队列
         * 参数四、是否自动删除(如果该队列没有生产者/消费者使用,那么该队列会自动删除)
         * 参数五、其它参数
         */
        channel.queueDeclare(QUEUE_NAME, false, false, true, null);

        // 消息成功投递时会回调该接口
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {

            try {
                /**
                 * 手动确认
                 * 参数一、消息标记
                 * 参数二、是否批量确认 true:应答所有消息,包括传递过来的消息 false:只应答传递过来的那个消息(接收到的那个消息)
                 */
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                String message = new String(delivery.getBody());
                log.info("接收到的消息是: {}", message);
            } catch (Exception e) {
                log.info("消费出错,出错的消息拒绝接收并重新进入队列");
                /**
                 * 参数一、消息标记
                 * 参数二、true:消费消息出错时拒绝消息,拒绝的消息将重新进入队列排队,false:不再重新进入队列排队
                 */
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), true);
            }
        };

        // 取消消费者时会回调该接口
        CancelCallback cancelCallback = (x) -> {
            log.info("取消消费者时会回调该接口");
        };

        /**
         * 参数一、队列名称
         * 参数二、true:自动确认 false:手动确认
         * 参数三、消息成功投递到队列的回调函数
         * 参数四、取消消费者时的回调函数
         */
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, cancelCallback);
    }
}

 六、测试过程及结果

1、先启动生产者发送消息

2、启动消费者消费消息

消费者控制台

 

 

posted @ 2021-11-09 16:27  变体精灵  阅读(34)  评论(0编辑  收藏  举报