package com.mz.controller;
import cn.hutool.crypto.SecureUtil;
import com.mz.domain.TMq;
import com.mz.service.TMqService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 马震
* @version 1.0
* @date 2023/11/28 10:19
*/
@RestController
@Slf4j
@RequestMapping("/mq")
public class MqController {
@Autowired
RocketMQTemplate rocketMQTemplate;
@Autowired
RedisTemplate redisTemplate;
@Autowired
TMqService tMqService;
@RequestMapping("send")
public void mqList(){
String body ="hello world";
extracted(body);//打包下面方法
}
private void extracted(String body) {
Message<String> message = MessageBuilder.withPayload(body).build();
rocketMQTemplate.asyncSend("mz_11_28", message, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
if(sendResult.getSendStatus().equals(SendStatus.SEND_OK)){
System.out.println("发送很成功"+message);
}else{ //说明没发送成功
log.info(body); //打印日志
TMq tMq = new TMq();
tMq.setBody(body);
tMqService.save(tMq); //持久化到表中
System.out.println("发送失败,没发送的消息是:"+body);
}
}
@Override
public void onException(Throwable throwable) {
System.out.println("连接异常");
String md5 = SecureUtil.md5(body);
Long increment = redisTemplate.opsForValue().increment(md5);//利用redis 里面的自增方法
System.out.println(increment);
//重新发送机制
if(increment<=3){
try {
Thread.sleep(1000*60); //每分钟重新发送一次
extracted(body);
System.err.println("重新发送第"+increment+"次");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else{ //重新发送超过3次了直接持久化到表中
log.info(body);
TMq tMq = new TMq();
tMq.setBody(body);
tMqService.save(tMq);
redisTemplate.delete(md5); //删除redis中那个键
System.out.println("没发送的消息是:"+body);
}
}
});
}
}
RocketMq的异步发送 重新发送问题解决
最新推荐文章于 2024-04-15 17:43:57 发布