1.RabbitMQ的安装
1.1.下载镜像
方式一:在线拉取
docker pull rabbitmq:3.8-management
方式二:从本地加载
上传到虚拟机中后,使用命令加载镜像即可:
docker load -i mq.tar
1.2.安装MQ
执行下面的命令来运行MQ容器:
docker run \ -e RABBITMQ_DEFAULT_USER=lwk \ -e RABBITMQ_DEFAULT_PASS=123456 \ -v mq-plugins:/plugins \ --name mq \ --hostname mq \ -p 15672:15672 \ -p 5672:5672 \ -d \ rabbitmq:3.8-management
2.SpringAMQP
SpringAMQP是基于RabbitMQ封装的一套模板,并且还利用SpringBoot对其实现了自动装配,使用起来非常方便。 SpringAmqp的官方地址:Spring AMQP
SpringAMQP提供了三个功能:
-
自动声明队列、交换机及其绑定关系
-
基于注解的监听器模式,异步接收消息
-
封装了RabbitTemplate工具,用于发送消息
2.1.Basic Queue 简单队列模型
在父工程mq-demo中引入依赖
<!--AMQP依赖,包含RabbitMQ--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
2.1.1.消息发送
首先配置MQ地址,在publisher服务的application.yml中添加配置:
spring: rabbitmq: host: 192.168.153.128 # 主机名 port: 5672 # 端口 virtual-host: / # 虚拟主机 username: lwk # 用户名 password: 123456 # 密码
然后在publisher服务中编写测试类SpringAmqpTest,并利用RabbitTemplate实现消息发送:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringAmqpTest { @Autowired private RabbitTemplate rabbitTemplate; @Test public void testSimpleQueue() { // 队列名称 String queueName = "simple.queue"; // 消息 String message = "hello, spring amqp!"; // 发送消息 rabbitTemplate.convertAndSend(queueName, message); } }
2.1.2.消息接收
首先配置MQ地址,在consumer服务的application.yml中添加配置:
spring: rabbitmq: host: 192.168.153.128 # 主机名 port: 5672 # 端口 virtual-host: / # 虚拟主机 username: lwk # 用户名 password: 123456 # 密码
然后在consumer服务的listener
包中新建一个类SpringRabbitListener,代码如下:
import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class SpringRabbitListener { @RabbitListener(queues = "simple.queue") public void listenSimpleQueueMessage(String msg) throws InterruptedException { System.out.println("spring 消费者接收到消息:【" + msg + "】"); } }
2.1.3.测试
启动consumer服务,然后在publisher服务中运行测试代码,发送MQ消息
2.2.WorkQueue
Work queues,也被称为(Task queuesÿ