RabbitMQ:SpringAMQP 入门案例
目录
- 一、概述
- 二、基础配置
- 三、生产者
- 四、消费者
一、概述
这是一篇Java集成RabbitMQ的入门案例,在这里我们做一个小案例,来体会一下RabbitMQ的魅力。
首先我们要做的就是创建一个生产者一个消费者:
- 生产者直接向RabbitMQ的队列(Queue)
simple.queue
中发送消息。 - 消费者负责接收队列(Queue)
simple.queue
发送过来的消息。
生产者源码
消费者源码
二、基础配置
当我们的生产者要发送和接收消息时,首先需要再RabbitMQ中创建一个通道。
三、生产者
- 加载POM文件
<dependencies><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>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
</dependencies>
- 配置YML文件
server:port: 8021
spring:#给项目来个名字application:name: rabbitmq-provider#配置rabbitMq 服务器rabbitmq:host: 127.0.0.1port: 5672username: adminpassword: adminvirtualHost: /mamfconnection-timeout: 5000requested-heartbeat: 30
- 在Test中编写测试代码
package com.ming;import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class SpringAmqpTest {@Autowiredprivate RabbitTemplate rabbitTemplate;@Testpublic void testSend() {for (int i = 0; i < 10; i++) {String queueName = "simple.queue"; // 队列名称String messahe = String.format("hello %s, spring amqp!", i + 1); // 消息rabbitTemplate.convertAndSend(queueName, messahe); // 发送}}
}
四、消费者
消费者的前两部分与生产者是一样的,消费者需要创建一个监听,用于监听simple.queue
队列。
package com.ming.listens;import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class RabbitmqListen {@RabbitListener(queues = "simple.queue")public void listenSimpleQueue(String message){System.out.println(String.format("消费者收到了simple.queue: %s", message));}
}
当从生产者发送消息时,消费者就会监听到数据。