Springboot快速集成RocketMQ
要在Spring Boot中快速集成RocketMQ,你需要做以下几步:
- 添加依赖:在
pom.xml
中添加RocketMQ的Spring Boot Starter依赖。
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.2.1</version>
</dependency>
- 配置RocketMQ:在
application.properties
或application.yml
中配置RocketMQ的基本信息。
# application.properties
spring.rocketmq.name-server=127.0.0.1:9876
spring.rocketmq.producer.group=my-group
- 发送消息:使用
@RocketMQMessageSender
注解自动创建的消息发送器发送消息。
import org.apache.rocketmq.spring.core.RocketMQTemplate;
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 {
@Autowired
private RocketMQTemplate rocketMQTemplate;
@GetMapping("/sendMessage")
public String sendMessage() {
rocketMQTemplate.convertAndSend("topic:test", "Hello, RocketMQ!");
return "Message sent.";
}
}
- 消费消息:使用
@RocketMQMessageListener
注解创建消息监听器来消费消息。
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
@Component
@RocketMQMessageListener(topic = "topic:test", consumerGroup = "my-consumer_test")
public class ConsumerListener implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
}
以上代码提供了一个简单的例子,展示了如何在Spring Boot应用中发送和接收RocketMQ消息。记得根据你的RocketMQ服务器地址和消费者组进行相应的配置。
评论已关闭