1.RocketMq安装部署
Linux 安装 RocketMq-CSDN博客文章来源:https://www.toymoban.com/news/detail-745316.html
2.添加依赖包
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.2.3</version>
</dependency>
3.配置
rocketmq:
name-server: 127.0.0.1:9876
# 生产者
producer:
group: group_one
# 消息发送超时时间
send-message-timeout: 30000
# 消息最大长度4M
max-message-size: 4096
# 消息发送失败重试次数
retry-times-when-send-failed: 3
# 异步消息发送失败重试次数
retry-times-when-send-async-failed: 2
# 消费者
consumer:
# 每次提取的最大消息数
pull-batch-size: 5
4.生成者代码
@RestController
@Slf4j
public class ProducerController {
@Resource
private RocketMQTemplate rocketMqTemplate;
@Resource
private DefaultMQProducer defaultMqProducer;
@GetMapping("/send/msg1/{messageBody}")
public String sendMsg1(@PathVariable("messageBody") String messageBody) {
// 发送消息
rocketMqTemplate.convertAndSend("topic1", messageBody);
return "OK";
}
@GetMapping("/send/msg2/{messageBody}")
public String sendMsg2(@PathVariable("messageBody") String messageBody) {
// 构建消息对象
Message message = new Message();
message.setTopic("topic2");
message.setTags("boot-mq-tag");
message.setKeys("boot-mq-key");
message.setBody(messageBody.getBytes());
// 发送消息,打印日志
SendResult sendResult = null;
try {
sendResult = defaultMqProducer.send(message);
log.info("sendMsg2 msgId:{},sendStatus:{}", sendResult.getMsgId(), sendResult.getSendStatus());
} catch (Exception e) {
log.info("sendMsg2 error", e);
return "FAIL";
}
return "OK";
}
}
5.消费者
@Component
@RocketMQMessageListener(topic = "topic1", consumerGroup = "topic1")
@Slf4j
public class MyTopic1Consumer implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
// 处理消息的逻辑
log.info("Received topic1 message: {}", message);
}
}
@Component
@RocketMQMessageListener(topic = "topic2", consumerGroup = "topic2")
@Slf4j
public class MyTopic2Consumer implements RocketMQListener<Message> {
@Override
public void onMessage(Message message) {
// 处理消息的逻辑
log.info("Received topic2 message: {}", new String(message.getBody()));
}
}
Springboot 集成 RocketMQ(进阶-消息)-CSDN博客文章来源地址https://www.toymoban.com/news/detail-745316.html
到了这里,关于Springboot 集成 RocketMq(入门)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!