MQ常量类
public interface MQConstants {
interface Topic{
String DELAY_AGAIN_DEDUCTION = "delay_again_deduction";
}
interface DelayLevel {
int level_1 = 1;
int level_2 = 2;
int level_3 = 3;
int level_4 = 4;
int level_5 = 5;
int level_6 = 6;
int level_7 = 7;
int level_8 = 8;
int level_9 = 9;
int level_10 = 10;
int level_11 = 11;
int level_12 = 12;
int level_13 = 13;
int level_14 = 14;
int level_15 = 15;
int level_16 = 16;
int level_17 = 17;
int level_18 = 18;
}
}
请求DTO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseMqDTO<T> implements Serializable {
private static final long serialVersionUID = -1L;
private T data;
private String messageId;
}
异步延时接口
public interface RemoteSaasMqService {
void convertAndSend(String topic, BaseMqDTO<?> data);
void sendDelayed(String topic, BaseMqDTO<?> data, int delayLevel);
}
异步实现类
@Slf4j
@DubboService
class RocketMQServiceImpl implements RemoteSaasMqService {
@Lazy
@Autowired
private RocketMQTemplate rocketMQTemplate;
@Override
public void convertAndSend(String topic, BaseMqDTO<?> data) {
rocketMQTemplate.asyncSend(topic, data, new SendCallback() {
@Override
public void onSuccess(SendResult res) {
log.info("convertAndSend - onSuccess - topic:{} data:{} sendResult:{}",topic, JSON.toJSONString(data),JSON.toJSONString(res));
}
@Override
public void onException(Throwable e) {
log.error("convertAndSend - onException - topic:{} data:{} e:",topic,JSON.toJSONString(data),e);
}
});
}
@Override
public void sendDelayed(String topic, BaseMqDTO<?> data, int delayLevel) {
rocketMQTemplate.asyncSend(topic, MessageBuilder.withPayload(data).build(), new SendCallback() {
@Override
public void onSuccess(SendResult res) {
log.info("sendDelayed - onSuccess - topic:{} data:{} sendResult:{}",topic,JSON.toJSONString(data),JSON.toJSONString(res));
}
@Override
public void onException(Throwable e) {
log.error("sendDelayed - onException - topic:{} data:{} e:",topic,JSON.toJSONString(data),e);
}
},5000,delayLevel);
}
}
异步发送请求
remoteSaasMqService.sendDelayed(MQConstants.Topic.DELAY_AGAIN_DEDUCTION,
new BaseMqDTO<>(传入你要消费的数据体, UUID.randomUUID().toString()),
MQConstants.DelayLevel.level_3);
MQ监听器接受数据
@Slf4j
@Component
@RocketMQMessageListener(topic = MQConstants.Topic.DELAY_AGAIN_DEDUCTION,consumerGroup = "${rocketmq.producer.group}" + "_" + MQConstants.Topic.DELAY_AGAIN_DEDUCTION)
public class DelayDeductionListener implements RocketMQListener<BaseMqDTO<DelayDeductionDTO>> {
@Override
public void onMessage(BaseMqDTO<DelayDeductionDTO> data) {
log.info("onMessage - data:{}", JSON.toJSONString(data));
circleDelay(data.getData());
}
}