Search in sources :

Example 6 with MQClientException

use of com.alibaba.rocketmq.client.exception.MQClientException in project druid by druid-io.

the class RocketMQFirehoseFactory method connect.

@Override
public Firehose connect(ByteBufferInputRowParser byteBufferInputRowParser) throws IOException, ParseException {
    Set<String> newDimExclus = Sets.union(byteBufferInputRowParser.getParseSpec().getDimensionsSpec().getDimensionExclusions(), Sets.newHashSet("feed"));
    final ByteBufferInputRowParser theParser = byteBufferInputRowParser.withParseSpec(byteBufferInputRowParser.getParseSpec().withDimensionsSpec(byteBufferInputRowParser.getParseSpec().getDimensionsSpec().withDimensionExclusions(newDimExclus)));
    /**
     * Topic-Queue mapping.
     */
    final ConcurrentHashMap<String, Set<MessageQueue>> topicQueueMap;
    /**
     * Default Pull-style client for RocketMQ.
     */
    final DefaultMQPullConsumer defaultMQPullConsumer;
    final DruidPullMessageService pullMessageService;
    messageQueueTreeSetMap.clear();
    windows.clear();
    try {
        defaultMQPullConsumer = new DefaultMQPullConsumer(this.consumerGroup);
        defaultMQPullConsumer.setMessageModel(MessageModel.CLUSTERING);
        topicQueueMap = new ConcurrentHashMap<>();
        pullMessageService = new DruidPullMessageService(defaultMQPullConsumer);
        for (String topic : feed) {
            Validators.checkTopic(topic);
            topicQueueMap.put(topic, defaultMQPullConsumer.fetchSubscribeMessageQueues(topic));
        }
        DruidMessageQueueListener druidMessageQueueListener = new DruidMessageQueueListener(Sets.newHashSet(feed), topicQueueMap, defaultMQPullConsumer);
        defaultMQPullConsumer.setMessageQueueListener(druidMessageQueueListener);
        defaultMQPullConsumer.start();
        pullMessageService.start();
    } catch (MQClientException e) {
        LOGGER.error("Failed to start DefaultMQPullConsumer", e);
        throw new IOException("Failed to start RocketMQ client", e);
    }
    return new Firehose() {

        @Override
        public boolean hasMore() {
            boolean hasMore = false;
            DruidPullRequest earliestPullRequest = null;
            for (Map.Entry<String, Set<MessageQueue>> entry : topicQueueMap.entrySet()) {
                for (MessageQueue messageQueue : entry.getValue()) {
                    if (JavaCompatUtils.keySet(messageQueueTreeSetMap).contains(messageQueue) && !messageQueueTreeSetMap.get(messageQueue).isEmpty()) {
                        hasMore = true;
                    } else {
                        try {
                            long offset = defaultMQPullConsumer.fetchConsumeOffset(messageQueue, false);
                            int batchSize = (null == pullBatchSize || pullBatchSize.isEmpty()) ? DEFAULT_PULL_BATCH_SIZE : Integer.parseInt(pullBatchSize);
                            DruidPullRequest newPullRequest = new DruidPullRequest(messageQueue, null, offset, batchSize, !hasMessagesPending());
                            // notify pull message service to pull messages from brokers.
                            pullMessageService.putRequest(newPullRequest);
                            // set the earliest pull in case we need to block.
                            if (null == earliestPullRequest) {
                                earliestPullRequest = newPullRequest;
                            }
                        } catch (MQClientException e) {
                            LOGGER.error("Failed to fetch consume offset for queue: {}", entry.getKey());
                        }
                    }
                }
            }
            // Block only when there is no locally pending messages.
            if (!hasMore && null != earliestPullRequest) {
                try {
                    earliestPullRequest.getCountDownLatch().await();
                    hasMore = true;
                } catch (InterruptedException e) {
                    LOGGER.error("CountDownLatch await got interrupted", e);
                }
            }
            return hasMore;
        }

        @Override
        public InputRow nextRow() {
            for (Map.Entry<MessageQueue, ConcurrentSkipListSet<MessageExt>> entry : messageQueueTreeSetMap.entrySet()) {
                if (!entry.getValue().isEmpty()) {
                    MessageExt message = entry.getValue().pollFirst();
                    InputRow inputRow = theParser.parse(ByteBuffer.wrap(message.getBody()));
                    if (!JavaCompatUtils.keySet(windows).contains(entry.getKey())) {
                        windows.put(entry.getKey(), new ConcurrentSkipListSet<Long>());
                    }
                    windows.get(entry.getKey()).add(message.getQueueOffset());
                    return inputRow;
                }
            }
            // should never happen.
            throw new RuntimeException("Unexpected Fatal Error! There should have been one row available.");
        }

        @Override
        public Runnable commit() {
            return new Runnable() {

                @Override
                public void run() {
                    OffsetStore offsetStore = defaultMQPullConsumer.getOffsetStore();
                    Set<MessageQueue> updated = new HashSet<>();
                    // calculate offsets according to consuming windows.
                    for (ConcurrentHashMap.Entry<MessageQueue, ConcurrentSkipListSet<Long>> entry : windows.entrySet()) {
                        while (!entry.getValue().isEmpty()) {
                            long offset = offsetStore.readOffset(entry.getKey(), ReadOffsetType.MEMORY_FIRST_THEN_STORE);
                            if (offset + 1 > entry.getValue().first()) {
                                entry.getValue().pollFirst();
                            } else if (offset + 1 == entry.getValue().first()) {
                                entry.getValue().pollFirst();
                                offsetStore.updateOffset(entry.getKey(), offset + 1, true);
                                updated.add(entry.getKey());
                            } else {
                                break;
                            }
                        }
                    }
                    offsetStore.persistAll(updated);
                }
            };
        }

        @Override
        public void close() throws IOException {
            defaultMQPullConsumer.shutdown();
            pullMessageService.shutdown(false);
        }
    };
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) DefaultMQPullConsumer(com.alibaba.rocketmq.client.consumer.DefaultMQPullConsumer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MQClientException(com.alibaba.rocketmq.client.exception.MQClientException) HashSet(java.util.HashSet) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) Firehose(io.druid.data.input.Firehose) IOException(java.io.IOException) ByteBufferInputRowParser(io.druid.data.input.ByteBufferInputRowParser) MessageExt(com.alibaba.rocketmq.common.message.MessageExt) MessageQueue(com.alibaba.rocketmq.common.message.MessageQueue) InputRow(io.druid.data.input.InputRow) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OffsetStore(com.alibaba.rocketmq.client.consumer.store.OffsetStore)

Example 7 with MQClientException

use of com.alibaba.rocketmq.client.exception.MQClientException in project warn-report by saaavsaaa.

the class PushConsumerServiceImpl method run.

@Override
public void run() throws MQClientException, InterruptedException {
    System.out.println("case : PushConsumerServiceImpl start");
    RocketListener listener = new RocketListener(receive);
    DefaultMQPushConsumer consumer;
    try {
        consumer = buildPushConsumer(namesrvAddr, consumerGroup, topic, subExpression, listener);
        consumer.start();
        System.out.println("case : consumer start");
    } catch (Exception e) {
        consumer = buildPushConsumer(namesrvAddrBak, consumerGroup, topic, subExpression, listener);
        consumer.start();
        System.out.println("case : consumerbak start, reason : consumer error" + e.getMessage());
    }
}
Also used : DefaultMQPushConsumer(com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer) MQClientException(com.alibaba.rocketmq.client.exception.MQClientException) RocketListener(rocketDoubleWrite.listener.RocketListener)

Example 8 with MQClientException

use of com.alibaba.rocketmq.client.exception.MQClientException in project warn-report by saaavsaaa.

the class TestProcess method TestPull.

@Test
public void TestPull() throws MQClientException {
    // "192.168.1.44:9876";
    final String address = "192.168.1.45:9876";
    final String topic = "topicTest";
    final String consumerGroup = "cgr";
    final String subExpression = "*";
    PullConsumer consumer = new PullConsumer(address, consumerGroup);
    Set<MessageQueue> mqs = consumer.getMessageQueue(topic);
    for (MessageQueue mq : mqs) {
        System.out.println("Consume from the queue: " + mq);
        SINGLE_MQ: while (true) {
            try {
                PullResult pullResult = consumer.pullBlockIfNotFound(mq, subExpression, getMessageQueueOffset(mq), 32);
                System.out.println(pullResult);
                putMessageQueueOffset(mq, pullResult.getNextBeginOffset());
                switch(pullResult.getPullStatus()) {
                    case FOUND:
                        List<MessageExt> msgs = pullResult.getMsgFoundList();
                        for (MessageExt ext : msgs) {
                            String key = ext.getKeys();
                            String keys = ext.getProperty("KEYS");
                            String value = new String(ext.getBody());
                            System.out.println("key : " + key + "; KEYS :" + keys + "; body : " + value + "\n");
                        }
                        break;
                    case NO_MATCHED_MSG:
                        break;
                    case NO_NEW_MSG:
                        break SINGLE_MQ;
                    case OFFSET_ILLEGAL:
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    for (Map.Entry<MessageQueue, Long> one : offseTable.entrySet()) {
        System.out.println(one.getValue());
    }
}
Also used : MessageExt(com.alibaba.rocketmq.common.message.MessageExt) MessageQueue(com.alibaba.rocketmq.common.message.MessageQueue) List(java.util.List) PullConsumer(rocket.PullConsumer) HashMap(java.util.HashMap) Map(java.util.Map) PullResult(com.alibaba.rocketmq.client.consumer.PullResult) MQBrokerException(com.alibaba.rocketmq.client.exception.MQBrokerException) RemotingException(com.alibaba.rocketmq.remoting.exception.RemotingException) MQClientException(com.alibaba.rocketmq.client.exception.MQClientException) Test(org.junit.Test)

Example 9 with MQClientException

use of com.alibaba.rocketmq.client.exception.MQClientException in project uavstack by uavorg.

the class TestRestService method testRocketmq.

@POST
@Path("testRocketmq")
public void testRocketmq(String jsonString) {
    DefaultMQProducer producer = new DefaultMQProducer("hookTest");
    producer.setNamesrvAddr("127.0.0.1:9876");
    Message msg = new Message("SELF_TEST_TOPIC", "test".getBytes());
    try {
        producer.start();
        for (int i = 0; i < 10; i++) {
            producer.send(msg);
        }
    } catch (MQClientException e) {
        e.printStackTrace();
    } catch (RemotingException e) {
        e.printStackTrace();
    } catch (MQBrokerException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    DefaultMQPushConsumer pushConsumer = new DefaultMQPushConsumer("hookTest");
    pushConsumer.setNamesrvAddr("127.0.0.1:9876");
    pushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    pushConsumer.registerMessageListener(new MessageListenerOrderly() {

        @Override
        public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
            System.out.println("haha");
            return ConsumeOrderlyStatus.SUCCESS;
        }
    });
    pushConsumer.registerMessageListener(new MessageListenerConcurrently() {

        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
            System.out.println("haha");
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });
    try {
        pushConsumer.subscribe("SELF_TEST_TOPIC", null);
        pushConsumer.start();
    } catch (MQClientException e1) {
        e1.printStackTrace();
    }
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    pushConsumer.shutdown();
    producer.shutdown();
}
Also used : MessageListenerConcurrently(com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently) Message(com.alibaba.rocketmq.common.message.Message) MessageListenerOrderly(com.alibaba.rocketmq.client.consumer.listener.MessageListenerOrderly) MQBrokerException(com.alibaba.rocketmq.client.exception.MQBrokerException) ConsumeConcurrentlyStatus(com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus) DefaultMQPushConsumer(com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer) ConsumeOrderlyContext(com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyContext) DefaultMQProducer(com.alibaba.rocketmq.client.producer.DefaultMQProducer) ConsumeConcurrentlyContext(com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext) MessageExt(com.alibaba.rocketmq.common.message.MessageExt) ConsumeOrderlyStatus(com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyStatus) RemotingException(com.alibaba.rocketmq.remoting.exception.RemotingException) MQClientException(com.alibaba.rocketmq.client.exception.MQClientException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 10 with MQClientException

use of com.alibaba.rocketmq.client.exception.MQClientException in project warn-report by saaavsaaa.

the class PushConsumerServiceImpl method run.

@Override
public void run() throws MQClientException, InterruptedException {
    System.out.println("case : PushConsumerServiceImpl start");
    RocketListener listener = new RocketListener(receive);
    DefaultMQPushConsumer consumer;
    try {
        consumer = buildPushConsumer(namesrvAddr, consumerGroup, topic, subExpression, listener);
        consumer.start();
        System.out.println("case : consumer start");
    } catch (Exception e) {
        consumer = buildPushConsumer(namesrvAddrBak, consumerGroup, topic, subExpression, listener);
        consumer.start();
        System.out.println("case : consumerbak start, reason : consumer error" + e.getMessage());
    }
}
Also used : DefaultMQPushConsumer(com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer) MQClientException(com.alibaba.rocketmq.client.exception.MQClientException) RocketListener(cn.tellwhy.third.rocketDoubleWrite.listener.RocketListener)

Aggregations

MQClientException (com.alibaba.rocketmq.client.exception.MQClientException)10 MessageExt (com.alibaba.rocketmq.common.message.MessageExt)8 DefaultMQPushConsumer (com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer)5 ConsumeConcurrentlyContext (com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext)5 MessageListenerConcurrently (com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently)5 MQBrokerException (com.alibaba.rocketmq.client.exception.MQBrokerException)5 RemotingException (com.alibaba.rocketmq.remoting.exception.RemotingException)5 List (java.util.List)4 Test (org.junit.Test)4 ConsumeConcurrentlyStatus (com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus)3 ConsumeOrderlyContext (com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyContext)3 ConsumeOrderlyStatus (com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyStatus)3 MessageListenerOrderly (com.alibaba.rocketmq.client.consumer.listener.MessageListenerOrderly)3 DefaultMQProducer (com.alibaba.rocketmq.client.producer.DefaultMQProducer)3 Message (com.alibaba.rocketmq.common.message.Message)3 MessageQueue (com.alibaba.rocketmq.common.message.MessageQueue)3 Map (java.util.Map)3 PullResult (com.alibaba.rocketmq.client.consumer.PullResult)2 HashMap (java.util.HashMap)2 POST (javax.ws.rs.POST)2