一、导入依赖库

  1. <dependency>
  2. <groupId>com.rabbitmq</groupId>
  3. <artifactId>amqp-client</artifactId>
  4. <version>5.9.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-amqp</artifactId>
  9. </dependency>

二、创建RabbitMQ配置类

连接 RabbitMQ 需要用到 ConnectionFactory ,所以我们要自己创建好 ConnectionFactory 对象 然后注册给Spring框架,这就需要我们创建 RabbitMQConfig 类。

@Configuration
public class RabbitMQConfig {
    @Bean
    public ConnectionFactory getFactory() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.99.101"); //Linux主机的IP地址
        factory.setPort(5672); //RabbitMQ端口号
        return factory;
    }
}

三、创建消息任务类

以前我们使用异步多线程的方式发送邮件,那么这次我们要创建的多线程任务类是用来收发 RabbitMQ消息的,而且内部包含了同步执行和异步执行两种方式。
image.png

package com.project.emos.wx.task;

import com.project.emos.wx.entity.MessageEntity;
import com.project.emos.wx.entity.MessageRefEntity;
import com.project.emos.wx.exception.EmosException;
import com.project.emos.wx.service.MessageService;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author JianqingWeng
 * @Description
 * @create 2021-06-22 9:34
 */
@Slf4j
@Component
public class MessageTask {

    @Autowired
    private ConnectionFactory factory;

    @Autowired
    private MessageService messageService;

    /**
     * 同步发送消息
     * @param topic 主题
     * @param entity
     */
    public void send(String topic, MessageEntity entity) {
        //向MongoDB保存消息数据,返回消息ID
        String id = messageService.insertMessage(entity);

        //向RabbitMQ发送消息
        Connection connection = null;
        Channel channel = null;
        try {
            // 创建一个 TCP 连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();

            // 连接到某个 Topic
            /**
             * (String queue, 如果 topic 队列不存在,则会创建这个队列
             * boolean durable, 是否进行持久化存储(放在硬盘而不是内存)
             * boolean exclusive, 是否给队列加锁
             * boolean autoDelete,
             * Map<String, Object> arguments)
             */
            channel.queueDeclare(topic, true, false, false, null);
            // 存放属性数据
            HashMap header = new HashMap();
            header.put("messageId", id);

            // 创建 AMQP 协议参数对象,添加附加属性(放到请求头里面)
            AMQP.BasicProperties properties = new AMQP.BasicProperties().
                                            builder().
                                            headers(header).
                                            build();

            channel.basicPublish("", topic, properties, entity.getMsg().getBytes());
            log.debug("消息发送成功");
        } catch (Exception e) {
            log.error("执行异常", e);
            throw new EmosException("向MQ发送消息失败");
        } finally {
            if (channel != null) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 异步发送消息
     * @param topic 主题
     * @param entity
     */
    @Async
    public void sendAsync(String topic, MessageEntity entity) {
        send(topic, entity);
    }

    /**
     * 同步接收数据
     * @param topic 主题, 队列名字
     * @return 接收消息数量
     */
    public int receive(String topic) {

        int count = 0;
        Connection connection = null;
        Channel channel = null;

        try {
            connection = factory.newConnection();
            channel = connection.createChannel();

            // 从队列中获取消息,不自动确认
            channel.queueDeclare(topic, true, false, false, null);

            //Topic中有多少条数据未知,所以使用死循环接收数据,直到接收不到消息,退出死循环
            while (true) {
                //创建响应接收数据,禁止自动发送Ack应答
                GetResponse response = channel.basicGet(topic, false);
                if (response != null) {
                    AMQP.BasicProperties properties = response.getProps();
                    //获取附加属性对象
                    Map<String, Object> header = properties.getHeaders();
                    // 获得 messageId
                    String messageId = header.get("messageId").toString();
                    byte[] body = response.getBody();//获取消息正文
                    String message = new String(body);
                    log.debug("从RabbitMQ接收的消息:" + message);
                    MessageRefEntity entity = new MessageRefEntity();
                    entity.setMessageId(messageId);
                    entity.setReceiverId(Integer.parseInt(topic));
                    // 消息未读
                    entity.setReadFlag(false);
                    // 最新消息
                    entity.setLastFlag(true);
                    //把消息存储在 MongoDB 中
                    messageService.insertRef(entity);
                    //数据保存到MongoDB后,才发送Ack应答,让Topic删除这条消息
                    long deliveryTag = response.getEnvelope().getDeliveryTag();
                    channel.basicAck(deliveryTag, false);
                    count += 1;
                }
                else {
                    break; //接收不到消息,则退出死循环
                }
            }
        } catch (Exception e) {
            log.error("执行异常", e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (channel != null) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return count;
    }

    /**
     * 异步接收数据
     * @param topic 主题, 队列名字
     * @return
     */
    @Async
    public int receiveAsync(String topic) {
        return receive(topic);
    }

    /**
     * 同步删除消息队列
     * @param topic 主题, 队列名字
     */
    public void deleteQueue(String topic) {

        Connection connection = null;
        Channel channel = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();

            channel.queueDelete(topic);
            log.debug("消息队列成功删除");
        } catch (Exception e) {
            log.error("删除队列失败", e);
            throw new EmosException("删除队列失败");
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (channel != null) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 异步删除消息队列
     * @param topic 主题,队列名字
     */
    @Async
    public void deleteQueueAsync(String topic) {
        deleteQueue(topic);
    }
}