整合RocketMQ到Spring Boot项目中涉及以下几个步骤:
-
添加依赖: 在
pom.xml
中添加RocketMQ的依赖:<dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
-
配置文件: 在
application.properties
或application.yml
中配置RocketMQ相关的属性,例如NameServer地址等。rocketmq.name-server=127.0.0.1:9876 rocketmq.producer.group=your-producer-group rocketmq.consumer.group=your-consumer-group
-
生产者代码: 定义一个RocketMQ生产者bean,用于发送消息。
import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class RocketMQProducer { @Autowired private RocketMQTemplate rocketMQTemplate; public void sendMessage(String topic, String message) { rocketMQTemplate.convertAndSend(topic, message); } }
-
消费者代码: 定义一个RocketMQ消费者,用于接收消息。
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.stereotype.Service; @Service @RocketMQMessageListener(topic = "your-topic", consumerGroup = "your-consumer-group") public class RocketMQConsumer implements RocketMQListener<String> { @Override public void onMessage(String message) { System.out.println("Received message: " + message); } }
-
运行RocketMQ: 确保RocketMQ的NameServer和Broker已经启动。可以参考RocketMQ官方文档进行配置和启动。
-
测试: 编写一个控制器或者服务来调用生产者发送消息,并观察消费者是否正确接收到消息。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired private RocketMQProducer rocketMQProducer; @GetMapping("/send") public String sendMessage(@RequestParam String message) { rocketMQProducer.sendMessage("your-topic", message); return "Message sent: " + message; } }
通过以上步骤,可以在Spring Boot项目中集成RocketMQ,实现消息的发送和接收功能。