All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.yes.tools.mq.rocket.RocketMqConsumer Maven / Gradle / Ivy

There is a newer version: 2.0.5
Show newest version
package org.yes.tools.mq.rocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.yes.tools.core.exception.YesBaseException;
import org.yes.tools.mq.annotaion.MQConsumer;
import org.yes.tools.mq.properties.RocketMQProperties;
import org.yes.tools.utils.StringUtil;

import java.util.Objects;

/**
 * 消费器
 *
 * @param 
 */
@Slf4j
public class RocketMqConsumer {
    private static DefaultMQPushConsumer consumer = null;

    @Autowired
    protected T messageListener;

    private String consumerGroup;
    private String topic = "";
    private String tag = "*";
    private MessageModel messageModel;


    {
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        MQConsumer annotation = this.getClass().getAnnotation(MQConsumer.class);
        if (Objects.isNull(annotation)) {
            throw new YesBaseException("请在extends RocketMqConsumer类上添加@MQConsumer注解");
        }
        if (StringUtil.isEmpty(annotation.topic())) {
            throw new YesBaseException("请在@MQConsumer注解上添加topic属性");
        }
        this.consumerGroup = annotation.consumerGroup();
        this.topic = annotation.topic();
        this.tag = annotation.tag();
        this.messageModel = annotation.model();
    }

    public DefaultMQPushConsumer getConsumer() throws MQClientException {
        //建消费者Consumer,制定消费者组名
        consumer = new DefaultMQPushConsumer(consumerGroup);
        //mq地址
        consumer.setNamesrvAddr(RocketMQProperties.NAMESRV_ADDR);
        //最大消费线程
        consumer.setConsumeThreadMax(RocketMQProperties.CONSUME_THREAD_MAX);
        //最小消费线程
        consumer.setConsumeThreadMin(RocketMQProperties.CONSUME_THREAD_MIN);
        //每次消费消息数量
        consumer.setConsumeMessageBatchMaxSize(RocketMQProperties.CONSUME_MESSAGE_BATCH_MAX_SIZE);
        consumer.setMessageModel(messageModel);
        //设置监听器
        //4.设置回调函数,处理消息
        // MessageListenerConcurrently  并发模式 多线程消费
        consumer.registerMessageListener(this.messageListener);
        try {
            consumer.subscribe(topic, tag);
            consumer.start();
            log.info("CONSUMER SUCCESSFULLY LAUNCHED TOPIC:{},TAG:{}", this.topic, this.tag);
        } catch (Exception e) {
            log.error("CONSUMER LAUNCH FAILED:{}", e.getMessage());
            throw e;
        }
        return consumer;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy