wordpress商品展示模板下载,邢台快照优化,要做好网络营销首先要,wordpress自动评论文章目录 需求 项目设置与依赖管理 配置RabbitMQ的连接信息创建队列与消息发送创建消费者#xff08;消息接收#xff09;环境准备与操作 需求
利用控制台创建队列 simple.queue在 publisher 服务中#xff0c;利用 SpringAMQP 直接向 simple.queue 发送消息在 consumer 服… 文章目录 需求 项目设置与依赖管理 配置RabbitMQ的连接信息创建队列与消息发送创建消费者消息接收环境准备与操作 需求
利用控制台创建队列 simple.queue在 publisher 服务中利用 SpringAMQP 直接向 simple.queue 发送消息在 consumer 服务中利用 SpringAMQP 编写消费者监听 simple.queue 队列 项目设置与依赖管理
在实际项目中通常我们会使用 spring-boot-starter-amqp 来引入Spring AMQP的功能。项目中的依赖配置已经包含了RabbitMQ的相关依赖所以不需要单独添加。
!--AMQP依赖包含RabbitMQ--
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-amqp/artifactId
/dependency配置RabbitMQ的连接信息
配置RabbitMQ连接的地址、端口和虚拟主机信息这些信息在 每个微服务的 application.yml 文件中进行设置。需要设置如下参数 spring.rabbitmq.hostRabbitMQ服务器的IP地址或域名。spring.rabbitmq.port连接RabbitMQ的端口通常为5672。spring.rabbitmq.virtual-hostRabbitMQ的虚拟主机。spring.rabbitmq.username 和 spring.rabbitmq.password连接RabbitMQ的用户名和密码。
spring:rabbitmq:host: 192.168.100.212 # 主机名port: 5672 # 端口virtual-host: / # 虚拟主机username: nhuan # 用户名password: 123456 # 密码创建队列与消息发送
创建队列在RabbitMQ控制台中创建一个简单的队列如 simple.q。发送消息 使用Spring AMQP提供的 RabbitTemplate 发送消息。调用 convertAndSend 方法其中需要指定队列名和消息内容。例子代码
Autowired
private RabbitTemplate rabbitTemplate;Test
public void testSimpleQueue() {// 队列名称String queueName simple.queue;// 消息String message Hello, Spring AMQP!;// 发送消息rabbitTemplate.convertAndSend(simple.queue, message);
}创建消费者消息接收
消费者用于监听队列并接收消息。创建一个类并使用 RabbitListener 注解标注接收方法指定监听的队列名称。例子代码
Slf4j
Component
public class SpringRabbitListener {RabbitListener(queues simple.queue)public void listenSimpleQueueMessage(String message) throws InterruptedException {log.info(spring 消费者接收到的消息: message);}
}通过 RabbitListener 注解Spring会自动处理消息的接收和转换。运行ConsumerApplication成功监测到消息 环境准备与操作
在开发过程中确保RabbitMQ服务已经启动并运行。消费者和生产者分别部署到不同的微服务中通过队列进行消息交换。