更新时间:2023-11-15 GMT+08:00
使用Spring Boot连接RabbitMQ实例
本文介绍如何使用Spring Boot连接RabbitMQ实例进行消息的生产和消费。
使用前请参考收集连接信息收集RabbitMQ所需的连接信息。
在pom.xml文件中引入spring-boot-starter-amqp依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.3.1.RELEASE</version> </dependency>
(可选)在application.properties文件中填写配置
如果RabbitMQ实例已开启SSL,在“application.properties”文件中填写如下配置。
#开启SSL认证 spring.rabbitmq.ssl.enabled=true #SSL使用的算法 spring.rabbitmq.ssl.algorithm=TLSv1.2 #是否启用主机验证 spring.rabbitmq.ssl.verify-hostname=false #是否启用服务端证书验证 spring.rabbitmq.ssl.validate-server-certificate=false
生产消息
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ProducerController { private static final Logger LOG = LoggerFactory.getLogger(ProducerController.class); @Autowired private RabbitTemplate; @GetMapping(value = "/send") public boolean send(String msg, Long delayTime) { rabbitTemplate.convertAndSend("ex-sour", "abc", msg, message -> { /** * 设置延迟时间 */ message.getMessageProperties().setHeader("x-delay", delayTime); return message; }); LOG.info("发送延迟消息:{},延时:{}ms", msg, delayTime); return true; } }
消费消息
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class ReceiveMsgService { Logger LOG = LoggerFactory.getLogger(ReceiveMsgService.class); @RabbitListener(queues = "test") public void receive(String message) { SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); LOG.info("receive message: {}", message + " 接收时间:" + simpleDateFormat.format(new Date())); } }