springboot集成rocketmq实战
时间: 2023-08-21 15:02:19 浏览: 122
要在Spring Boot中集成RocketMQ,您可以按照以下步骤进行操作:
1. 添加RocketMQ依赖:在您的Spring Boot项目的`pom.xml`文件中,添加以下依赖:
```xml
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
```
2. 配置RocketMQ参数:在`application.properties`(或`application.yml`)文件中,添加RocketMQ的相关配置信息,例如:
```properties
# NameServer地址,多个地址用逗号分隔
rocketmq.name-server=127.0.0.1:9876
# 生产者组名
rocketmq.producer.group=my-producer-group
# 消费者组名
rocketmq.consumer.group=my-consumer-group
# 消费者订阅的Topic和Tag,多个Topic和Tag用分号分隔
rocketmq.consumer.topics=my-topic:tag1;my-topic:tag2
```
3. 创建RocketMQ生产者:在需要发送消息的地方,创建一个RocketMQ生产者,例如:
```java
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("/send")
public String sendMessage() {
rocketMQTemplate.convertAndSend("my-topic", "Hello, RocketMQ!");
return "Message sent successfully!";
}
}
```
4. 创建RocketMQ消费者:创建一个RocketMQ消费者,例如:
```java
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
@Component
@RocketMQMessageListener(topic = "my-topic", consumerGroup = "my-consumer-group")
public class Consumer implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
5. 运行应用程序:启动Spring Boot应用程序,并访问`/send`端点,将发送一条消息到RocketMQ。消费者将接收并打印该消息。
这样,您就成功地在Spring Boot中集成了RocketMQ,并实现了消息的发布和订阅。您可以根据需要进一步扩展和定制RocketMQ的使用。
阅读全文