springboot rocketmq 发送quenen
时间: 2023-10-12 21:19:50 浏览: 181
在Spring Boot中使用RocketMQ发送消息到队列需要进行以下步骤:
1. 添加RocketMQ的依赖,可以在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>com.aliyun.openservices</groupId>
<artifactId>ons-client</artifactId>
<version>1.7.7</version>
</dependency>
```
2. 配置RocketMQ的相关信息,可以在application.properties中添加以下配置:
```properties
#RocketMQ Namesrv地址
rocketmq.namesrvAddr=your.namesrvAddr
#RocketMQ Producer Group
rocketmq.producerGroup=your.producerGroup
```
3. 创建一个消息生产者,示例代码如下:
```java
import com.aliyun.openservices.ons.api.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Properties;
@Component
public class RocketMQProducer {
@Value("${rocketmq.namesrvAddr}")
private String namesrvAddr;
@Value("${rocketmq.producerGroup}")
private String producerGroup;
private Producer producer;
@PostConstruct
public void init() {
Properties properties = new Properties();
properties.put(PropertyKeyConst.GROUP_ID, producerGroup);
properties.put(PropertyKeyConst.NAMESRV_ADDR, namesrvAddr);
// 初始化Producer,需要指定消息序列化方式,默认为JSON序列化
producer = ONSFactory.createProducer(properties, new JsonMessageSerializer());
producer.start();
}
@PreDestroy
public void destroy() {
producer.shutdown();
}
public void send(String topic, String tag, Object data) {
Message message = new Message(topic, tag, data.toString().getBytes());
SendResult sendResult = producer.send(message);
System.out.println("消息ID:" + sendResult.getMessageId() + ",发送状态:" + sendResult.getSendStatus());
}
}
```
4. 调用send方法发送消息,示例代码如下:
```java
rocketMQProducer.send("yourTopic", "yourTag", "yourData");
```
这样就可以在Spring Boot中使用RocketMQ发送消息到队列了。
阅读全文