我们以前发送消息是直接由发送方(Provider)直接发向接收方(Consumer),当使用队列了之后,就有发送方发给队列(Queue),然后有队列转发给接收方(Consumer)。队列就作为消息的中转站,起到存储消息,以及转发的功能。
对应 RabbitMQ 就不做多的说明了。下面直接开始搭建项目,看看 RabbitMQ 的实现的例子。
工程结构
项目搭建
pom.xml 文件修改
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置文件修改
application.properties
spring.application.name=springboot-amqp
server.port=8080
spring.rabbitmq.host=192.168.1.101
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456
## 这里是我在 docker 启动的时候,设置了一个 virtual host,可以根据自己的实际情况来设置
spring.rabbitmq.virtual-host=my_vhost
创建队列,用于转发发送方的消息
SenderConfig.java
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SenderConfig {
@Bean
public Queue queue(){
// 这里创建一个 名字为 hello-world-queue 的队列
return new Queue("hello-world-queue");
}
}
创建发送者,用于向队列中发送消息
Sender.java
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitTemplate;
// 通过 AmqpTemplate 向队列中发送消息
public void send(){
String msg = "sender " + LocalDate.now();
// 向指定队列中发送消息
this.rabbitTemplate.convertAndSend("hello-world-queue", msg);
}
}
创建接收者,用于接收指定对列中的消息
Receiver.java
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
// 使用 RabbitListener 来监听指定队列中的消息
@RabbitListener(queues = {"hello-world-queue"})
public void process(String msg){
System.out.println("Receiver" + msg);
}
}
测试类
import org.junit.Test;
import org.junit.runner.RunWith;
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(classes = BootRabbitmqApplication.class)
public class BootRabbitmqApplicationTests {
@Autowired
private Sender sender;
@Test
public void contextLoads() {
this.sender.send();
}
}
启动测试类,在控制台,就可以看到发送的消息了
我们进入管理界面,可以看到我们刚刚创建完的队列