踩了3天的坑,發現使用rocketMQTemplte消費者一直註冊不上,發現是springboot版本問題
1.版本選擇
經過不嚴格測試發現
rocketmq-spring-boot-starter 2.3.0 支援 springboot3以上
rocketmq-spring-boot-starter 2.2.x 只能使用3以下,高版本會導致消費者註冊不上的問題
2.application.yml
rocketmq:
name-server: 127.0.0.1:9876
# 生產者
producer:
group: myProducer
# 訊息傳送超時時間
send-message-timeout: 3000
# 訊息最大長度4M
max-message-size: 4096
# 訊息傳送失敗重試次數
retry-times-when-send-failed: 3
# 非同步訊息傳送失敗重試次數
retry-times-when-send-async-failed: 2
# 消費者
consumer:
group: myConsumer
# 每次提取的最大訊息數
3.配置類
@Configuration
public class RocketMqConfig {
@Value("${rocketmq.name-server}")
private String nameServer;
@Value("${rocketmq.producer.group}")
private String producerGroup;
@Value("${rocketmq.producer.send-message-timeout}")
private Integer sendMsgTimeout;
@Value("${rocketmq.producer.max-message-size}")
private Integer maxMessageSize;
@Value("${rocketmq.producer.retry-times-when-send-failed}")
private Integer retryTimesWhenSendFailed ;
@Value("${rocketmq.producer.retry-times-when-send-async-failed}")
private Integer retryTimesWhenSendAsyncFailed ;
@Bean
public RocketMQTemplate rocketMqTemplate(){
RocketMQTemplate rocketMqTemplate = new RocketMQTemplate();
rocketMqTemplate.setProducer(defaultMqProducer());
return rocketMqTemplate;
}
@Bean
public DefaultMQProducer defaultMqProducer() {
DefaultMQProducer producer = new DefaultMQProducer();
producer.setNamesrvAddr(this.nameServer);
producer.setProducerGroup(this.producerGroup);
producer.setSendMsgTimeout(this.sendMsgTimeout);
producer.setMaxMessageSize(this.maxMessageSize);
producer.setRetryTimesWhenSendFailed(this.retryTimesWhenSendFailed);
producer.setRetryTimesWhenSendAsyncFailed(this.retryTimesWhenSendAsyncFailed);
return producer;
}
}
4.生產者
@Component
public class OrderSaveProducer {
@Autowired
private RocketMQTemplate rocketMqTemplate;
public String sendSaveOrder() throws Exception {
SendResult sendResult = rocketMqTemplate.syncSend("saveOrderTopic",json);
return sendResult.getMsgId();
}
}
5.消費者
@Component
@RocketMQMessageListener(consumerGroup = ("saveOrderConsumer"), topic = ("saveOrderTopic"))
public class OrderSaveConsumer implements RocketMQListener<MessageExt> {
@Override
public void onMessage(MessageExt messageExt) {
try{
// 獲取訊息
byte[] body = messageExt.getBody();
OrderInfo orderInfo = JSON.parseObject(new String(body), OrderInfo.class);
System.out.println(orderInfo);
}catch (Exception e){
e.printStackTrace();
}
}
}