Search in sources :

Example 11 with MessageExt

use of org.apache.rocketmq.common.message.MessageExt in project spring-boot-starter-samples by vindell.

the class ScheduledMessageConsumer method main.

public static void main(String[] args) throws Exception {
    // Instantiate message consumer
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("ExampleConsumer");
    // Subscribe topics
    consumer.subscribe("TestTopic", "*");
    // Register message listener
    consumer.registerMessageListener(new MessageListenerConcurrently() {

        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
            for (MessageExt message : messages) {
                // Print approximate delay time period
                System.out.println("Receive message[msgId=" + message.getMsgId() + "] " + (System.currentTimeMillis() - message.getStoreTimestamp()) + "ms later");
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });
    // Launch consumer
    consumer.start();
}
Also used : ConsumeConcurrentlyContext(org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext) MessageExt(org.apache.rocketmq.common.message.MessageExt) MessageListenerConcurrently(org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently) ConsumeConcurrentlyStatus(org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus) DefaultMQPushConsumer(org.apache.rocketmq.client.consumer.DefaultMQPushConsumer)

Example 12 with MessageExt

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

the class MessageServiceImplTest method messageTrackDetail.

@Test
public void messageTrackDetail() throws Exception {
    final String messageId = msgId;
    Pair<MessageView, List<MessageTrack>> messageViewListPair = new RetryTempLate<Pair<MessageView, List<MessageTrack>>>() {

        @Override
        protected Pair<MessageView, List<MessageTrack>> process() throws Exception {
            return messageService.viewMessage(TEST_CONSOLE_TOPIC, messageId);
        }
    }.execute(10, // make the topic can be found
    1000);
    final MessageExt messageExt = mqAdminExt.viewMessage(TEST_CONSOLE_TOPIC, messageId);
    Assert.assertNotNull(messageService.messageTrackDetail(messageExt));
}
Also used : MessageExt(org.apache.rocketmq.common.message.MessageExt) MessageView(org.apache.rocketmq.console.model.MessageView) MessageTrack(org.apache.rocketmq.tools.admin.api.MessageTrack) List(java.util.List) Pair(org.apache.rocketmq.common.Pair) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 13 with MessageExt

use of org.apache.rocketmq.common.message.MessageExt 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 14 with MessageExt

use of org.apache.rocketmq.common.message.MessageExt 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 15 with MessageExt

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

the class JmsMessageConvertTest method testCovert2RMQ.

@Test
public void testCovert2RMQ() throws Exception {
    // init jmsBaseMessage
    String topic = "TestTopic";
    String messageType = "TagA";
    JmsBaseMessage jmsBaseMessage = new JmsTextMessage("testText");
    jmsBaseMessage.setHeader(JmsBaseConstant.JMS_DESTINATION, new JmsBaseTopic(topic, messageType));
    jmsBaseMessage.setHeader(JmsBaseConstant.JMS_MESSAGE_ID, "ID:null");
    jmsBaseMessage.setHeader(JmsBaseConstant.JMS_REDELIVERED, Boolean.FALSE);
    jmsBaseMessage.setObjectProperty(MsgConvertUtil.JMS_MSGMODEL, MsgConvertUtil.MSGMODEL_TEXT);
    jmsBaseMessage.setObjectProperty(MsgConvertUtil.MSG_TOPIC, topic);
    jmsBaseMessage.setObjectProperty(MsgConvertUtil.MSG_TYPE, messageType);
    jmsBaseMessage.setObjectProperty(MessageConst.PROPERTY_TAGS, messageType);
    jmsBaseMessage.setObjectProperty(MessageConst.PROPERTY_KEYS, messageType);
    // convert to RMQMessage
    MessageExt message = (MessageExt) MessageConverter.convert2RMQMessage(jmsBaseMessage);
    System.out.println(message);
    // then convert back to jmsBaseMessage
    JmsBaseMessage jmsBaseMessageBack = MessageConverter.convert2JMSMessage(message);
    JmsTextMessage jmsTextMessage = (JmsTextMessage) jmsBaseMessage;
    JmsTextMessage jmsTextMessageBack = (JmsTextMessage) jmsBaseMessageBack;
    Assert.assertEquals(jmsTextMessage.getText(), jmsTextMessageBack.getText());
    Assert.assertEquals(jmsTextMessage.getJMSDestination().toString(), jmsTextMessageBack.getJMSDestination().toString());
    Assert.assertEquals(jmsTextMessage.getJMSMessageID(), jmsTextMessageBack.getJMSMessageID());
    Assert.assertEquals(jmsTextMessage.getJMSRedelivered(), jmsTextMessageBack.getJMSRedelivered());
    Assert.assertEquals(jmsTextMessage.getHeaders().get(MsgConvertUtil.JMS_MSGMODEL), jmsTextMessageBack.getHeaders().get(MsgConvertUtil.JMS_MSGMODEL));
    Assert.assertEquals(jmsTextMessage.getHeaders().get(MsgConvertUtil.MSG_TOPIC), jmsTextMessageBack.getHeaders().get(MsgConvertUtil.MSG_TOPIC));
    Assert.assertEquals(jmsTextMessage.getHeaders().get(MsgConvertUtil.MSG_TYPE), jmsTextMessageBack.getHeaders().get(MsgConvertUtil.MSG_TYPE));
    Assert.assertEquals(jmsTextMessage.getHeaders().get(MessageConst.PROPERTY_TAGS), jmsTextMessageBack.getHeaders().get(MessageConst.PROPERTY_TAGS));
    Assert.assertEquals(jmsTextMessage.getHeaders().get(MessageConst.PROPERTY_KEYS), jmsTextMessageBack.getHeaders().get(MessageConst.PROPERTY_KEYS));
}
Also used : MessageExt(org.apache.rocketmq.common.message.MessageExt) JmsBaseTopic(org.apache.rocketmq.jms.domain.JmsBaseTopic) Test(org.junit.Test)

Aggregations

MessageExt (org.apache.rocketmq.common.message.MessageExt)23 DefaultMQPushConsumer (org.apache.rocketmq.client.consumer.DefaultMQPushConsumer)7 PullResult (org.apache.rocketmq.client.consumer.PullResult)7 MQClientException (org.apache.rocketmq.client.exception.MQClientException)7 MessageQueue (org.apache.rocketmq.common.message.MessageQueue)7 Test (org.junit.Test)7 ConsumeConcurrentlyContext (org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext)6 ConsumeConcurrentlyStatus (org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus)6 MessageListenerConcurrently (org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently)6 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 List (java.util.List)4 DefaultMQPullConsumer (org.apache.rocketmq.client.consumer.DefaultMQPullConsumer)4 MqConsumerStore (com.paascloud.provider.annotation.MqConsumerStore)3 Date (java.util.Date)3 Event (org.apache.flume.Event)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Map (java.util.Map)2 Context (org.apache.flume.Context)2 Sink (org.apache.flume.Sink)2