Search in sources :

Example 21 with RemotingException

use of org.apache.rocketmq.remoting.exception.RemotingException in project rocketmq-externals by apache.

the class WorkerSourceTask method sendRecord.

/**
 * Send list of sourceDataEntries to MQ.
 *
 * @param sourceDataEntries
 */
private void sendRecord(Collection<SourceDataEntry> sourceDataEntries) {
    for (SourceDataEntry sourceDataEntry : sourceDataEntries) {
        ByteBuffer partition = sourceDataEntry.getSourcePartition();
        Optional<ByteBuffer> opartition = Optional.ofNullable(partition);
        ByteBuffer position = sourceDataEntry.getSourcePosition();
        Optional<ByteBuffer> oposition = Optional.ofNullable(position);
        sourceDataEntry.setSourcePartition(null);
        sourceDataEntry.setSourcePosition(null);
        Message sourceMessage = new Message();
        sourceMessage.setTopic(sourceDataEntry.getQueueName());
        if (null == recordConverter || recordConverter instanceof RocketMQConverter) {
            if (StringUtils.isNotEmpty(sourceDataEntry.getShardingKey())) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SHARDINGKEY, sourceDataEntry.getShardingKey());
            }
            if (StringUtils.isNotEmpty(sourceDataEntry.getQueueName())) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_TOPICNAME, sourceDataEntry.getQueueName());
            }
            if (opartition.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SOURCE_PARTITION, new String(opartition.get().array()));
            }
            if (oposition.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SOURCE_POSITION, new String(oposition.get().array()));
            }
            EntryType entryType = sourceDataEntry.getEntryType();
            Optional<EntryType> oentryType = Optional.ofNullable(entryType);
            if (oentryType.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_ENTRYTYPE, oentryType.get().name());
            }
            Long timestamp = sourceDataEntry.getTimestamp();
            Optional<Long> otimestamp = Optional.ofNullable(timestamp);
            if (otimestamp.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_TIMESTAMP, otimestamp.get().toString());
            }
            Schema schema = sourceDataEntry.getSchema();
            Optional<Schema> oschema = Optional.ofNullable(schema);
            if (oschema.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SCHEMA, JSON.toJSONString(oschema.get()));
            }
            Object[] payload = sourceDataEntry.getPayload();
            if (null != payload && null != payload[0]) {
                Object object = payload[0];
                final byte[] messageBody = (String.valueOf(object)).getBytes();
                if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
                    log.error("Send record, message size is greater than {} bytes, payload: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, sourceDataEntry.getPayload());
                    return;
                }
                sourceMessage.setBody(messageBody);
            }
        } else {
            byte[] payload = recordConverter.objectToByte(sourceDataEntry.getPayload());
            Object[] newPayload = new Object[1];
            newPayload[0] = Base64.getEncoder().encodeToString(payload);
            sourceDataEntry.setPayload(newPayload);
            final byte[] messageBody = JSON.toJSONString(sourceDataEntry).getBytes();
            if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
                log.error("Send record, message size is greater than {} bytes, payload: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, sourceDataEntry.getPayload());
                return;
            }
            sourceMessage.setBody(messageBody);
        }
        try {
            producer.send(sourceMessage, new SendCallback() {

                @Override
                public void onSuccess(org.apache.rocketmq.client.producer.SendResult result) {
                    log.info("Successful send message to RocketMQ:{}", result.getMsgId());
                    try {
                        if (null != partition && null != position) {
                            positionManagementService.putPosition(partition, position);
                        }
                    } catch (Exception e) {
                        log.error("Source task save position info failed.", e);
                    }
                }

                @Override
                public void onException(Throwable throwable) {
                    if (null != throwable) {
                        log.error("Source task send record failed {}.", throwable);
                    }
                }
            });
        } catch (MQClientException e) {
            log.error("Send message error. message: {}, error info: {}.", sourceMessage, e);
        } catch (RemotingException e) {
            log.error("Send message error. message: {}, error info: {}.", sourceMessage, e);
        } catch (InterruptedException e) {
            log.error("Send message error. message: {}, error info: {}.", sourceMessage, e);
        }
    }
}
Also used : Message(org.apache.rocketmq.common.message.Message) Schema(io.openmessaging.connector.api.data.Schema) MQClientException(org.apache.rocketmq.client.exception.MQClientException) SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) ByteBuffer(java.nio.ByteBuffer) RocketMQConverter(org.apache.rocketmq.connect.runtime.converter.RocketMQConverter) MQClientException(org.apache.rocketmq.client.exception.MQClientException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) EntryType(io.openmessaging.connector.api.data.EntryType) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) SendCallback(org.apache.rocketmq.client.producer.SendCallback)

Example 22 with RemotingException

use of org.apache.rocketmq.remoting.exception.RemotingException in project spring-boot-starter-samples by vindell.

the class ConsumerListen method testListen.

@EventListener(condition = "#event.topic=='test'")
public void testListen(RocketmqEvent event) {
    MQPushConsumer consumer = consumerTemplate.getConsumer();
    try {
        String id = new String(event.getMessageExt().getBody(), "utf-8");
        System.out.println("bl" + id);
    } catch (Exception e) {
        e.printStackTrace();
        if (event.getMessageExt().getReconsumeTimes() <= 1) {
            // 重复消费1次
            try {
                consumer.sendMessageBack(event.getMessageExt(), 1, null);
            } catch (RemotingException | MQBrokerException | InterruptedException | MQClientException e1) {
                e1.printStackTrace();
            // 消息进行定时重试
            }
        } else {
            System.out.println("消息消费失败,定时重试");
        }
    }
}
Also used : DefaultMQPushConsumer(org.apache.rocketmq.client.consumer.DefaultMQPushConsumer) MQPushConsumer(org.apache.rocketmq.client.consumer.MQPushConsumer) MQClientException(org.apache.rocketmq.client.exception.MQClientException) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) EventListener(org.springframework.context.event.EventListener)

Example 23 with RemotingException

use of org.apache.rocketmq.remoting.exception.RemotingException in project rocketmq-externals by apache.

the class TestController method list.

@RequestMapping(value = "/runTask.do", method = RequestMethod.GET)
@ResponseBody
public Object list() throws MQClientException, RemotingException, InterruptedException {
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(testTopic + "Group");
    consumer.setNamesrvAddr(rMQConfigure.getNamesrvAddr());
    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    consumer.subscribe(testTopic, "*");
    consumer.registerMessageListener(new MessageListenerConcurrently() {

        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
            logger.info("receiveMessage msgSize={}", msgs.size());
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });
    consumer.start();
    final DefaultMQProducer producer = new DefaultMQProducer(testTopic + "Group");
    producer.setInstanceName(String.valueOf(System.currentTimeMillis()));
    producer.setNamesrvAddr(rMQConfigure.getNamesrvAddr());
    producer.start();
    new Thread(new Runnable() {

        @Override
        public void run() {
            int i = 0;
            while (true) {
                try {
                    Message msg = new Message(testTopic, "TagA" + i, "KEYS" + i, ("Hello RocketMQ " + i).getBytes());
                    Thread.sleep(1000L);
                    SendResult sendResult = producer.send(msg);
                    logger.info("sendMessage={}", JsonUtil.obj2String(sendResult));
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        Thread.sleep(1000);
                    } catch (Exception ignore) {
                    }
                }
            }
        }
    }).start();
    return true;
}
Also used : MessageListenerConcurrently(org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently) Message(org.apache.rocketmq.common.message.Message) ConsumeConcurrentlyStatus(org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus) DefaultMQPushConsumer(org.apache.rocketmq.client.consumer.DefaultMQPushConsumer) DefaultMQProducer(org.apache.rocketmq.client.producer.DefaultMQProducer) MQClientException(org.apache.rocketmq.client.exception.MQClientException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) ConsumeConcurrentlyContext(org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext) MessageExt(org.apache.rocketmq.common.message.MessageExt) SendResult(org.apache.rocketmq.client.producer.SendResult) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 24 with RemotingException

use of org.apache.rocketmq.remoting.exception.RemotingException in project rocketmq-externals by apache.

the class MQAdminExtImpl method viewMessage.

// MessageClientIDSetter.getNearlyTimeFromID has bug,so we subtract half a day
// next version we will remove it
// https://issues.apache.org/jira/browse/ROCKETMQ-111
// https://github.com/apache/incubator-rocketmq/pull/69
@Override
public MessageExt viewMessage(String topic, String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    logger.info("MessageClientIDSetter.getNearlyTimeFromID(msgId)={} msgId={}", MessageClientIDSetter.getNearlyTimeFromID(msgId), msgId);
    try {
        return viewMessage(msgId);
    } catch (Exception e) {
    }
    MQAdminImpl mqAdminImpl = MQAdminInstance.threadLocalMqClientInstance().getMQAdminImpl();
    QueryResult qr = Reflect.on(mqAdminImpl).call("queryMessage", topic, msgId, 32, MessageClientIDSetter.getNearlyTimeFromID(msgId).getTime() - 1000 * 60 * 60 * 13L, Long.MAX_VALUE, true).get();
    if (qr != null && qr.getMessageList() != null && qr.getMessageList().size() > 0) {
        return qr.getMessageList().get(0);
    } else {
        return null;
    }
}
Also used : QueryResult(org.apache.rocketmq.client.QueryResult) MQAdminImpl(org.apache.rocketmq.client.impl.MQAdminImpl) MQClientException(org.apache.rocketmq.client.exception.MQClientException) RemotingConnectException(org.apache.rocketmq.remoting.exception.RemotingConnectException) RemotingSendRequestException(org.apache.rocketmq.remoting.exception.RemotingSendRequestException) RemotingTimeoutException(org.apache.rocketmq.remoting.exception.RemotingTimeoutException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) RemotingCommandException(org.apache.rocketmq.remoting.exception.RemotingCommandException) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException)

Example 25 with RemotingException

use of org.apache.rocketmq.remoting.exception.RemotingException in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class StatsAllSubCommand method printTopicDetail.

public static void printTopicDetail(final DefaultMQAdminExt admin, final String topic, final boolean activeTopic) throws RemotingException, MQClientException, InterruptedException, MQBrokerException {
    TopicRouteData topicRouteData = admin.examineTopicRouteInfo(topic);
    GroupList groupList = admin.queryTopicConsumeByWho(topic);
    double inTPS = 0;
    long inMsgCntToday = 0;
    for (BrokerData bd : topicRouteData.getBrokerDatas()) {
        String masterAddr = bd.getBrokerAddrs().get(MixAll.MASTER_ID);
        if (masterAddr != null) {
            try {
                BrokerStatsData bsd = admin.viewBrokerStatsData(masterAddr, BrokerStatsManager.TOPIC_PUT_NUMS, topic);
                inTPS += bsd.getStatsMinute().getTps();
                inMsgCntToday += compute24HourSum(bsd);
            } catch (Exception e) {
            }
        }
    }
    if (groupList != null && !groupList.getGroupList().isEmpty()) {
        for (String group : groupList.getGroupList()) {
            double outTPS = 0;
            long outMsgCntToday = 0;
            for (BrokerData bd : topicRouteData.getBrokerDatas()) {
                String masterAddr = bd.getBrokerAddrs().get(MixAll.MASTER_ID);
                if (masterAddr != null) {
                    try {
                        String statsKey = String.format("%s@%s", topic, group);
                        BrokerStatsData bsd = admin.viewBrokerStatsData(masterAddr, BrokerStatsManager.GROUP_GET_NUMS, statsKey);
                        outTPS += bsd.getStatsMinute().getTps();
                        outMsgCntToday += compute24HourSum(bsd);
                    } catch (Exception e) {
                    }
                }
            }
            long accumulate = 0;
            try {
                ConsumeStats consumeStats = admin.examineConsumeStats(group, topic);
                if (consumeStats != null) {
                    accumulate = consumeStats.computeTotalDiff();
                    if (accumulate < 0) {
                        accumulate = 0;
                    }
                }
            } catch (Exception e) {
            }
            if (!activeTopic || (inMsgCntToday > 0) || (outMsgCntToday > 0)) {
                // 第二个参数默认是32,有时候消费者长度过长显示不去,修改为52
                System.out.printf("%-32s  %-52s %12d %11.2f %11.2f %14d %14d%n", UtilAll.frontStringAtLeast(topic, 32), // 有时候消费者长度过长显示不去,修改为52
                UtilAll.frontStringAtLeast(group, 52), accumulate, inTPS, outTPS, inMsgCntToday, outMsgCntToday);
            }
        }
    } else {
        if (!activeTopic || (inMsgCntToday > 0)) {
            // 第二个参数默认是32,有时候消费者长度过长显示不去,修改为52
            System.out.printf("%-32s  %-52s %12d %11.2f %11s %14d %14s%n", UtilAll.frontStringAtLeast(topic, 52), "", 0, inTPS, "", inMsgCntToday, "NO_CONSUMER");
        }
    }
}
Also used : GroupList(org.apache.rocketmq.common.protocol.body.GroupList) BrokerData(org.apache.rocketmq.common.protocol.route.BrokerData) ConsumeStats(org.apache.rocketmq.common.admin.ConsumeStats) SubCommandException(org.apache.rocketmq.tools.command.SubCommandException) MQClientException(org.apache.rocketmq.client.exception.MQClientException) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) TopicRouteData(org.apache.rocketmq.common.protocol.route.TopicRouteData) BrokerStatsData(org.apache.rocketmq.common.protocol.body.BrokerStatsData)

Aggregations

RemotingException (org.apache.rocketmq.remoting.exception.RemotingException)45 MQBrokerException (org.apache.rocketmq.client.exception.MQBrokerException)39 MQClientException (org.apache.rocketmq.client.exception.MQClientException)39 SendResult (org.apache.rocketmq.client.producer.SendResult)13 Message (org.apache.rocketmq.common.message.Message)13 RemotingTimeoutException (org.apache.rocketmq.remoting.exception.RemotingTimeoutException)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)9 RemotingConnectException (org.apache.rocketmq.remoting.exception.RemotingConnectException)9 MessageQueue (org.apache.rocketmq.common.message.MessageQueue)8 Test (org.junit.Test)8 RemotingCommandException (org.apache.rocketmq.remoting.exception.RemotingCommandException)7 RemotingSendRequestException (org.apache.rocketmq.remoting.exception.RemotingSendRequestException)7 IOException (java.io.IOException)6 SendMessageContext (org.apache.rocketmq.client.hook.SendMessageContext)6 DefaultMQProducer (org.apache.rocketmq.client.producer.DefaultMQProducer)6 SendMessageRequestHeader (org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader)6 SubscriptionData (org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData)6 RemotingCommand (org.apache.rocketmq.remoting.protocol.RemotingCommand)6 SubCommandException (org.apache.rocketmq.tools.command.SubCommandException)6 MessageExt (org.apache.rocketmq.common.message.MessageExt)5