spring boot 集成rocketmq
时间: 2023-09-11 20:09:03 浏览: 112
Spring Boot可以很方便地集成RocketMQ,可以通过以下步骤实现:
1. 在pom.xml中添加RocketMQ的依赖:
```xml
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>${rocketmq.version}</version>
</dependency>
```
2. 在application.properties中配置RocketMQ相关信息:
```properties
spring.rocketmq.name-server=127.0.0.1:9876
spring.rocketmq.producer.group=producer_group
spring.rocketmq.consumer.group=consumer_group
```
3. 创建消息生产者:
```java
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.stereotype.Component;
@Component
public class Producer {
@Autowired
private RocketMQTemplate rocketMQTemplate;
public void send(String message) {
Message<String> msg = MessageBuilder.withPayload(message).build();
rocketMQTemplate.send("topic", msg);
}
}
```
4. 创建消息消费者:
```java
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
@Component
@RocketMQMessageListener(topic = "topic", consumerGroup = "consumer_group")
public class Consumer implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
5. 在需要发送消息的地方调用Producer的send方法即可:
```java
@Autowired
private Producer producer;
public void sendMsg() {
producer.send("Hello RocketMQ!");
}
```
6. 启动应用程序,即可发送和接收RocketMQ消息。
阅读全文