package com.qmth.themis.mq.listener;

import com.qmth.themis.business.constant.SystemConstant;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Description: rocketmq 动态注册消费者
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/8
 */
@Component
public class RocketMessageConsumer {
    private final static Logger log = LoggerFactory.getLogger(RocketMessageConsumer.class);

    /**
     * 注册rocketmq 消费者
     *
     * @param nameSrvAddr
     * @param consumerGroupName
     * @param topic
     * @param tag
     * @param messageModel
     * @param o
     * @return
     */
    public DefaultMQPushConsumer setRocketMQConsumer(String nameSrvAddr, String consumerGroupName, String topic, String tag, MessageModel messageModel, Object o) {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerGroupName);
        consumer.setNamesrvAddr(nameSrvAddr);
        consumer.setConsumeMessageBatchMaxSize(SystemConstant.CONSUME_MESSAGE_BATCH_MAX_SIZE);//每次拉取10条
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.setMaxReconsumeTimes(SystemConstant.MAXRECONSUMETIMES);//最大重试次数
        consumer.setMessageModel(messageModel);
        if (o instanceof MessageListenerConcurrently) {
            consumer.registerMessageListener((MessageListenerConcurrently) o);
        } else if (o instanceof MessageListenerOrderly) {
            consumer.registerMessageListener((MessageListenerOrderly) o);
        }
        try {
            consumer.subscribe(topic, tag);
            consumer.start();
            log.info("consumer is start !!! groupName:{},topic:{},tag:{},namesrvAddr:{}", consumerGroupName, topic, tag, nameSrvAddr);
        } catch (MQClientException e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
        return consumer;
    }
}
