Search in sources :

Example 6 with MessageQueue

use of org.apache.rocketmq.common.message.MessageQueue in project rocketmq-externals by apache.

the class RocketMQSource method doProcess.

@Override
protected Status doProcess() throws EventDeliveryException {
    List<Event> events = new ArrayList<>();
    Map<MessageQueue, Long> offsets = new HashMap<>();
    Event event;
    Map<String, String> headers;
    try {
        Set<MessageQueue> queues = consumer.fetchSubscribeMessageQueues(topic);
        for (MessageQueue queue : queues) {
            long offset = getMessageQueueOffset(queue);
            PullResult pullResult = consumer.pull(queue, tag, offset, batchSize);
            if (log.isDebugEnabled()) {
                log.debug("Pull from queueId:{}, offset:{}, pullResult:{}", queue.getQueueId(), offset, pullResult);
            }
            if (pullResult.getPullStatus() == PullStatus.FOUND) {
                for (MessageExt msg : pullResult.getMsgFoundList()) {
                    byte[] body = msg.getBody();
                    headers = new HashMap<>();
                    headers.put(HEADER_TOPIC_NAME, topic);
                    headers.put(HEADER_TAG_NAME, tag);
                    if (log.isDebugEnabled()) {
                        log.debug("Processing message,body={}", new String(body, "UTF-8"));
                    }
                    event = EventBuilder.withBody(body, headers);
                    events.add(event);
                }
                offsets.put(queue, pullResult.getNextBeginOffset());
            }
        }
        if (events.size() > 0) {
            sourceCounter.incrementAppendBatchReceivedCount();
            sourceCounter.addToEventReceivedCount(events.size());
            getChannelProcessor().processEventBatch(events);
            sourceCounter.incrementAppendBatchAcceptedCount();
            sourceCounter.addToEventAcceptedCount(events.size());
            events.clear();
        }
        for (Map.Entry<MessageQueue, Long> entry : offsets.entrySet()) {
            putMessageQueueOffset(entry.getKey(), entry.getValue());
        }
    } catch (Exception e) {
        log.error("Failed to consumer message", e);
        return Status.BACKOFF;
    }
    return Status.READY;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PullResult(org.apache.rocketmq.client.consumer.PullResult) MQClientException(org.apache.rocketmq.client.exception.MQClientException) EventDeliveryException(org.apache.flume.EventDeliveryException) ConfigurationException(org.apache.flume.conf.ConfigurationException) FlumeException(org.apache.flume.FlumeException) MessageExt(org.apache.rocketmq.common.message.MessageExt) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) Event(org.apache.flume.Event) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with MessageQueue

use of org.apache.rocketmq.common.message.MessageQueue in project rocketmq-externals by apache.

the class ConsumerServiceImpl method queryConsumeStatsList.

@Override
@MultiMQAdminCmdMethod
public List<TopicConsumerInfo> queryConsumeStatsList(final String topic, String groupName) {
    ConsumeStats consumeStats = null;
    try {
        consumeStats = mqAdminExt.examineConsumeStats(groupName, topic);
    } catch (Exception e) {
        throw propagate(e);
    }
    List<MessageQueue> mqList = Lists.newArrayList(Iterables.filter(consumeStats.getOffsetTable().keySet(), new Predicate<MessageQueue>() {

        @Override
        public boolean apply(MessageQueue o) {
            return StringUtils.isBlank(topic) || o.getTopic().equals(topic);
        }
    }));
    Collections.sort(mqList);
    List<TopicConsumerInfo> topicConsumerInfoList = Lists.newArrayList();
    TopicConsumerInfo nowTopicConsumerInfo = null;
    Map<MessageQueue, String> messageQueueClientMap = getClientConnection(groupName);
    for (MessageQueue mq : mqList) {
        if (nowTopicConsumerInfo == null || (!StringUtils.equals(mq.getTopic(), nowTopicConsumerInfo.getTopic()))) {
            nowTopicConsumerInfo = new TopicConsumerInfo(mq.getTopic());
            topicConsumerInfoList.add(nowTopicConsumerInfo);
        }
        QueueStatInfo queueStatInfo = QueueStatInfo.fromOffsetTableEntry(mq, consumeStats.getOffsetTable().get(mq));
        queueStatInfo.setClientInfo(messageQueueClientMap.get(mq));
        nowTopicConsumerInfo.appendQueueStatInfo(queueStatInfo);
    }
    return topicConsumerInfoList;
}
Also used : QueueStatInfo(org.apache.rocketmq.console.model.QueueStatInfo) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) ConsumeStats(org.apache.rocketmq.common.admin.ConsumeStats) TopicConsumerInfo(org.apache.rocketmq.console.model.TopicConsumerInfo) MQClientException(org.apache.rocketmq.client.exception.MQClientException) Predicate(com.google.common.base.Predicate) MultiMQAdminCmdMethod(org.apache.rocketmq.console.aspect.admin.annotation.MultiMQAdminCmdMethod)

Example 8 with MessageQueue

use of org.apache.rocketmq.common.message.MessageQueue in project rocketmq-externals by apache.

the class RocketMQSource method run.

@Override
public void run(SourceContext context) throws Exception {
    LOG.debug("source run....");
    // The lock that guarantees that record emission and state updates are atomic,
    // from the view of taking a checkpoint.
    final Object lock = context.getCheckpointLock();
    int delayWhenMessageNotFound = getInteger(props, RocketMQConfig.CONSUMER_DELAY_WHEN_MESSAGE_NOT_FOUND, RocketMQConfig.DEFAULT_CONSUMER_DELAY_WHEN_MESSAGE_NOT_FOUND);
    String tag = props.getProperty(RocketMQConfig.CONSUMER_TAG, RocketMQConfig.DEFAULT_CONSUMER_TAG);
    int pullPoolSize = getInteger(props, RocketMQConfig.CONSUMER_PULL_POOL_SIZE, RocketMQConfig.DEFAULT_CONSUMER_PULL_POOL_SIZE);
    int pullBatchSize = getInteger(props, RocketMQConfig.CONSUMER_BATCH_SIZE, RocketMQConfig.DEFAULT_CONSUMER_BATCH_SIZE);
    pullConsumerScheduleService.setPullThreadNums(pullPoolSize);
    pullConsumerScheduleService.registerPullTaskCallback(topic, new PullTaskCallback() {

        @Override
        public void doPullTask(MessageQueue mq, PullTaskContext pullTaskContext) {
            try {
                long offset = getMessageQueueOffset(mq);
                if (offset < 0) {
                    return;
                }
                PullResult pullResult = consumer.pull(mq, tag, offset, pullBatchSize);
                boolean found = false;
                switch(pullResult.getPullStatus()) {
                    case FOUND:
                        List<MessageExt> messages = pullResult.getMsgFoundList();
                        for (MessageExt msg : messages) {
                            byte[] key = msg.getKeys() != null ? msg.getKeys().getBytes(StandardCharsets.UTF_8) : null;
                            byte[] value = msg.getBody();
                            OUT data = schema.deserializeKeyAndValue(key, value);
                            // output and state update are atomic
                            synchronized (lock) {
                                context.collectWithTimestamp(data, msg.getBornTimestamp());
                            }
                        }
                        found = true;
                        break;
                    case NO_MATCHED_MSG:
                        LOG.debug("No matched message after offset {} for queue {}", offset, mq);
                        break;
                    case NO_NEW_MSG:
                        break;
                    case OFFSET_ILLEGAL:
                        LOG.warn("Offset {} is illegal for queue {}", offset, mq);
                        break;
                    default:
                        break;
                }
                synchronized (lock) {
                    putMessageQueueOffset(mq, pullResult.getNextBeginOffset());
                }
                if (found) {
                    // no delay when messages were found
                    pullTaskContext.setPullNextDelayTimeMillis(0);
                } else {
                    pullTaskContext.setPullNextDelayTimeMillis(delayWhenMessageNotFound);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
    try {
        pullConsumerScheduleService.start();
    } catch (MQClientException e) {
        throw new RuntimeException(e);
    }
    runningChecker.setRunning(true);
    awaitTermination();
}
Also used : TypeHint(org.apache.flink.api.common.typeinfo.TypeHint) PullResult(org.apache.rocketmq.client.consumer.PullResult) MQClientException(org.apache.rocketmq.client.exception.MQClientException) MessageExt(org.apache.rocketmq.common.message.MessageExt) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) PullTaskContext(org.apache.rocketmq.client.consumer.PullTaskContext) PullTaskCallback(org.apache.rocketmq.client.consumer.PullTaskCallback) List(java.util.List) MQClientException(org.apache.rocketmq.client.exception.MQClientException)

Example 9 with MessageQueue

use of org.apache.rocketmq.common.message.MessageQueue in project rocketmq-externals by apache.

the class RocketMQSinkTest method testEvent.

@Test
public void testEvent() throws MQClientException, InterruptedException, EventDeliveryException, RemotingException, MQBrokerException, UnsupportedEncodingException {
    /*
        start sink
         */
    Context context = new Context();
    context.put(NAME_SERVER_CONFIG, nameServer);
    context.put(TAG_CONFIG, tag);
    RocketMQSink sink = new RocketMQSink();
    Configurables.configure(sink, context);
    MemoryChannel channel = new MemoryChannel();
    Configurables.configure(channel, context);
    sink.setChannel(channel);
    sink.start();
    /*
        mock flume source
         */
    String sendMsg = "\"Hello RocketMQ\"" + "," + DateFormatUtils.format(new Date(), "yyyy-MM-DD hh:mm:ss");
    Transaction tx = channel.getTransaction();
    tx.begin();
    Event event = EventBuilder.withBody(sendMsg.getBytes(), null);
    channel.put(event);
    tx.commit();
    tx.close();
    log.info("publish message : {}", sendMsg);
    Sink.Status status = sink.process();
    if (status == Sink.Status.BACKOFF) {
        fail("Error");
    }
    sink.stop();
    /*
        consumer message
         */
    consumer = new DefaultMQPullConsumer(consumerGroup);
    consumer.setNamesrvAddr(nameServer);
    consumer.setMessageModel(MessageModel.valueOf("BROADCASTING"));
    consumer.registerMessageQueueListener(TOPIC_DEFAULT, null);
    consumer.start();
    String receiveMsg = null;
    Set<MessageQueue> queues = consumer.fetchSubscribeMessageQueues(TOPIC_DEFAULT);
    for (MessageQueue queue : queues) {
        long offset = getMessageQueueOffset(queue);
        PullResult pullResult = consumer.pull(queue, tag, offset, 32);
        if (pullResult.getPullStatus() == PullStatus.FOUND) {
            for (MessageExt message : pullResult.getMsgFoundList()) {
                byte[] body = message.getBody();
                receiveMsg = new String(body, "UTF-8");
                log.info("receive message : {}", receiveMsg);
            }
            long nextBeginOffset = pullResult.getNextBeginOffset();
            putMessageQueueOffset(queue, nextBeginOffset);
        }
    }
    /*
        wait for processQueueTable init
         */
    Thread.sleep(1000);
    consumer.shutdown();
    assertEquals(sendMsg, receiveMsg);
}
Also used : Context(org.apache.flume.Context) MemoryChannel(org.apache.flume.channel.MemoryChannel) Date(java.util.Date) DefaultMQPullConsumer(org.apache.rocketmq.client.consumer.DefaultMQPullConsumer) PullResult(org.apache.rocketmq.client.consumer.PullResult) MessageExt(org.apache.rocketmq.common.message.MessageExt) Transaction(org.apache.flume.Transaction) Sink(org.apache.flume.Sink) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) Event(org.apache.flume.Event) Test(org.junit.Test)

Example 10 with MessageQueue

use of org.apache.rocketmq.common.message.MessageQueue in project rocketmq-externals by apache.

the class BinlogPositionManager method initPositionFromMqTail.

private void initPositionFromMqTail() throws Exception {
    DefaultMQPullConsumer consumer = new DefaultMQPullConsumer("BINLOG_CONSUMER_GROUP");
    consumer.setNamesrvAddr(config.mqNamesrvAddr);
    consumer.setMessageModel(MessageModel.valueOf("BROADCASTING"));
    consumer.start();
    Set<MessageQueue> queues = consumer.fetchSubscribeMessageQueues(config.mqTopic);
    MessageQueue queue = queues.iterator().next();
    if (queue != null) {
        Long offset = consumer.maxOffset(queue);
        if (offset > 0)
            offset--;
        PullResult pullResult = consumer.pull(queue, "*", offset, 100);
        if (pullResult.getPullStatus() == PullStatus.FOUND) {
            MessageExt msg = pullResult.getMsgFoundList().get(0);
            String json = new String(msg.getBody(), "UTF-8");
            JSONObject js = JSON.parseObject(json);
            binlogFilename = (String) js.get("binlogFilename");
            nextPosition = js.getLong("nextPosition");
        }
    }
}
Also used : MessageExt(org.apache.rocketmq.common.message.MessageExt) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) JSONObject(com.alibaba.fastjson.JSONObject) DefaultMQPullConsumer(org.apache.rocketmq.client.consumer.DefaultMQPullConsumer) PullResult(org.apache.rocketmq.client.consumer.PullResult)

Aggregations

MessageQueue (org.apache.rocketmq.common.message.MessageQueue)11 PullResult (org.apache.rocketmq.client.consumer.PullResult)7 MessageExt (org.apache.rocketmq.common.message.MessageExt)7 MQClientException (org.apache.rocketmq.client.exception.MQClientException)5 DefaultMQPullConsumer (org.apache.rocketmq.client.consumer.DefaultMQPullConsumer)4 Date (java.util.Date)3 List (java.util.List)3 Event (org.apache.flume.Event)3 Test (org.junit.Test)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Context (org.apache.flume.Context)2 Sink (org.apache.flume.Sink)2 Transaction (org.apache.flume.Transaction)2 MemoryChannel (org.apache.flume.channel.MemoryChannel)2 MultiMQAdminCmdMethod (org.apache.rocketmq.console.aspect.admin.annotation.MultiMQAdminCmdMethod)2 JSONObject (com.alibaba.fastjson.JSONObject)1 Function (com.google.common.base.Function)1 Predicate (com.google.common.base.Predicate)1