当你使用Spring Boot集成RocketMQ时,你需要依赖一些相关的库,并配置一些必要的属性。以下是一个简单的步骤,包括依赖、配置和代码示例:
步骤 1: 添加依赖
在你的Spring Boot项目中,打开 pom.xml 文件,添加RocketMQ的相关依赖:
<dependencies>
<!-- Spring Boot Starter for RocketMQ -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.2.0</version> <!-- 请根据实际情况选择最新版本 -->
</dependency>
</dependencies>
步骤 2: 配置 RocketMQ
在 application.properties 或 application.yml 中添加RocketMQ的配置:
# RocketMQ Nameserver 地址
rocketmq.name-server=your-nameserver-address
# 指定消费者组名
rocketmq.consumer.group=your-consumer-group
替换 your-nameserver-address 和 your-consumer-group 为你的RocketMQ Nameserver地址和消费者组名。
步骤 3: 创建消息生产者
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MessageProducerController {
@Autowired
private RocketMQTemplate rocketMQTemplate;
@GetMapping("/sendMessage/{message}")
public String sendMessage(@PathVariable String message) {
// 发送消息到指定的 Topic
rocketMQTemplate.convertAndSend("your-topic", message);
return "Message sent successfully!";
}
}
替换 your-topic 为你的RocketMQ Topic。
步骤 4: 创建消息消费者
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
@Component
@RocketMQMessageListener(topic = "your-topic", consumerGroup = "your-consumer-group")
public class MessageConsumer implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
// 处理接收到的消息
System.out.println("Received message: " + message);
}
}
确保替换 your-topic 和 your-consumer-group 为你的RocketMQ Topic和消费者组名。
以上代码是一个简单的示例,实际项目中可能需要根据需求做更多的配置和处理。此外,确保RocketMQ服务器正常运行,并在你的项目中正确配置RocketMQ的连接信息。