RocketMQ+Springboot整合及简单原理

话不多说,直接主题

pom文件新增:


    org.apache.rocketmq
    rocketmq-spring-boot-starter
    2.0.3


    org.apache.rocketmq
    rocketmq-client
    4.5.2


    org.apache.rocketmq
    rocketmq-common
    4.5.2

生产消息:

@Slf4j
@Service
public class MQServiceImpl implements MQService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public SendResult sendMsg(String topic, String tags,String keys, String body, int delayTimeLevel) {
        SendResult sendResult = null;
        //消息体
        Message message = new Message(topic, tags, keys, body.getBytes());
        message.setDelayTimeLevel(delayTimeLevel);
        try {
            sendResult = rocketMQTemplate.getProducer().send(message);
            if (!sendResult.getSendStatus().equals(SendStatus.SEND_OK)){
//            失败重试一次
                sendResult = rocketMQTemplate.getProducer().send(message);
            }
           log.info("发送结果:{}", JSONObject.toJSONString(sendResult));
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       return sendResult;
    }
}

消费消息:

/**
 * 消息监听
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.closeOrder.topic}", consumerGroup = "${mq.order.closeOrder.consumer.group.name}",
        messageModel = MessageModel.CLUSTERING, consumeMode = ConsumeMode.ORDERLY, consumeThreadMax = 20)
public class CloseOrderListener implements RocketMQListener {
    @Autowired
    private TbEmbeddedSingleService tbEmbeddedSingleService;
    @Value("${mq.order.closeOrder.topic}")
    private String topic;

    @Value("${mq.order.closeOrder.failed.tag}")
    private String failedTag;

    @Autowired
    private MQService mqService;

    @Override
    public void onMessage(MessageExt message) {
        TbEmbeddedSingle tbEmbeddedSingle = null;
        try {
            String body = new String(message.getBody(), StandardCharsets.UTF_8);
            tbEmbeddedSingle = JSON.parseObject(body, TbEmbeddedSingle.class);
            log.info("收到消息:{}", JSONObject.toJSONString(tbEmbeddedSingle));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

原理解析:消费端是有线程池去拿消息消费的,定义了线程池数量及队列类型

RocketMQ+Springboot整合及简单原理_第1张图片

只看到消息的拿,消息失败怎么处理呢?,下图,会打印出每次消息消费时间,如果消费失败,会从0级别延迟开始试,重试

 

RocketMQ+Springboot整合及简单原理_第2张图片

你可能感兴趣的:(工具总结,java,spring,boot)