Spring Boot对接RocketMQ5.0
在Spring Boot中对接RocketMQ 5.0,你需要做以下几个步骤:
- 添加依赖:在
pom.xml
中添加RocketMQ Spring Boot的依赖和RocketMQ客户端的依赖。
<dependencies>
<!-- RocketMQ Spring Boot Starter -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.2.1</version>
</dependency>
<!-- RocketMQ Client -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>5.0.0</version>
</dependency>
</dependencies>
- 配置RocketMQ:在
application.properties
或application.yml
中配置RocketMQ的基本信息。
# application.properties
spring.rocketmq.name-server=127.0.0.1:9876
spring.rocketmq.producer.group=my-group
- 发送消息:创建一个Service来发送消息到RocketMQ。
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RocketMQService {
@Autowired
private RocketMQTemplate rocketMQTemplate;
public void sendMessage(String topic, String tag, String message) {
rocketMQTemplate.send(topic, tag, message);
}
}
- 接收消息:创建一个Listener来监听RocketMQ的消息。
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 ConsumerListener implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
// 处理接收到的消息
System.out.println("Received message: " + message);
}
}
确保你的RocketMQ服务器正在运行,并且配置的name-server
地址是正确的。上述代码提供了一个简单的例子,展示了如何在Spring Boot应用中发送和接收RocketMQ消息。
评论已关闭