代码方式
第一步方式导入依赖的方式
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--AMQP依赖,包含RabbitMQ--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency></dependencies>
原理,mq需要消费者(Publisher)发送消息,服务方式(Consumer)接受消息方式
yml 配置方式
spring:rabbitmq:host: 192.168.36.128 #主机端口port: 5672virtual-host: / #虚拟主机username: itcastpassword: 123321
server:port: 1020
Publisher 调用api 方式 RabbitTemplate
@Autowiredprivate RabbitTemplate rabbitTemplate;@GetMapping("/testSimpleQueue")public void testSimpleQueue() {String queueName = "simple.queue";for (int i = 0; i < 50; i++) {String message = "hello, spring amqp!"+i;rabbitTemplate.convertAndSend(queueName, message);}}
说明 rabbitTemplate.convertAndSend(queueName, message);
queueName 队列名称,如何找到队列名称,这个队列名称,mq自动创建,只需要在发送消息,在消息接受方有对应的队列就可以
message 发送消息
Consumer 服务的接受方式
yml 配置方式
spring:rabbitmq:listener:simple:prefetch: 1host: 192.168.36.128port: 5672virtual-host: /username: itcastpassword: 123321
server:port: 1010
consumer 接收者代码
@Component
public class SpringRabbitListener {@RabbitListener(queues = "simple.queue")public void listenSimpleQueueMessage(String msg) throws InterruptedException {System.out.println("spring 1----------:【" + msg + "】"+ LocalTime.now());Thread.sleep(20);}@RabbitListener(queues = "simple.queue")public void listenSimpleQueueMessageTwo(String msg) throws InterruptedException {System.out.println("spring 2------:【" + msg + "】"+ LocalTime.now());Thread.sleep(1000);}}
解释 RabbitListener 中的队列参数名称queues
queues队列的参数名称
目录结构