婚恋网站女生要求男生要一起做淘宝,平面广告设计论文,通江县网站建设,公司网站建设的目的文章目录 要引入spring-boot-starter-amqp依赖才能开始后续操作 1. 配置RabbitMQ地址2. 编写消息发送测试类3. 实现消息接收 在本文中#xff0c;我们将介绍如何在Spring Boot应用中使用RabbitMQ实现消息的发送与接收。我们将创建两个服务#xff0c;一个用于发送消息#x… 文章目录 要引入spring-boot-starter-amqp依赖才能开始后续操作 1. 配置RabbitMQ地址2. 编写消息发送测试类3. 实现消息接收 在本文中我们将介绍如何在Spring Boot应用中使用RabbitMQ实现消息的发送与接收。我们将创建两个服务一个用于发送消息Publisher服务一个用于接收消息Consumer服务。首先我们需要在这两个服务中配置RabbitMQ地址接着编写发送和接收消息的代码。 要引入spring-boot-starter-amqp依赖才能开始后续操作
1. 配置RabbitMQ地址
首先在Publisher服务的application.yml文件中添加RabbitMQ的配置
spring:rabbitmq:host: # 你的虚拟机IPport: # 端口virtual-host: # 虚拟主机username: # 用户名password: # 密码2. 编写消息发送测试类
在Publisher服务中我们需要编写一个测试类SpringAmqpTest并利用RabbitTemplate实现消息的发送
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 testSimpleQueue() {// 队列名称String queueName simple.queue;// 消息String message hello, spring amqp!;// 发送消息rabbitTemplate.convertAndSend(queueName, message);}
}运行测试后打开控制台你将看到消息已经成功发送到队列中。
3. 实现消息接收
同样地在Consumer服务的application.yml文件中添加RabbitMQ的配置
spring:rabbitmq:host: # 你的虚拟机IPport: # 端口virtual-host: # 虚拟主机username: # 用户名password: # 密码接下来在Consumer服务的com.itheima.consumer.listener包中新建一个类SpringRabbitListener用于监听队列并处理消息
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;Component
public class SpringRabbitListener {// 利用RabbitListener来声明要监听的队列信息// 一旦监听的队列中有了消息就会推送给当前服务调用当前方法处理消息。// 可以看到方法体中接收的就是消息体的内容RabbitListener(queues simple.queue)public void listenSimpleQueueMessage(String msg) {System.out.println(spring 消费者接收到消息【 msg 】);}
}运行后当队列simple.queue中有消息时SpringRabbitListener中的listenSimpleQueueMessage方法将被调用并输出接收到的消息内容。