Search in sources :

Example 56 with TopicRouteData

use of org.apache.rocketmq.common.protocol.route.TopicRouteData in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MQClientInstance method updateTopicRouteInfoFromNameServer.

public boolean updateTopicRouteInfoFromNameServer(final String topic, boolean isDefault, DefaultMQProducer defaultMQProducer) {
    try {
        if (this.lockNamesrv.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
            try {
                TopicRouteData topicRouteData;
                if (isDefault && defaultMQProducer != null) {
                    topicRouteData = this.mQClientAPIImpl.getDefaultTopicRouteInfoFromNameServer(defaultMQProducer.getCreateTopicKey(), // 获取topic规则
                    1000 * 3);
                    if (topicRouteData != null) {
                        for (QueueData data : topicRouteData.getQueueDatas()) {
                            int queueNums = Math.min(defaultMQProducer.getDefaultTopicQueueNums(), data.getReadQueueNums());
                            data.setReadQueueNums(queueNums);
                            data.setWriteQueueNums(queueNums);
                        }
                    }
                } else {
                    topicRouteData = this.mQClientAPIImpl.getTopicRouteInfoFromNameServer(topic, 1000 * 3);
                }
                if (topicRouteData != null) {
                    TopicRouteData old = this.topicRouteTable.get(topic);
                    boolean changed = topicRouteDataIsChange(old, topicRouteData);
                    if (!changed) {
                        changed = this.isNeedUpdateTopicRouteInfo(topic);
                    } else {
                        log.info("the topic[{}] route info changed, old[{}] ,new[{}]", topic, old, topicRouteData);
                    }
                    if (changed) {
                        TopicRouteData cloneTopicRouteData = topicRouteData.cloneTopicRouteData();
                        for (BrokerData bd : topicRouteData.getBrokerDatas()) {
                            this.brokerAddrTable.put(bd.getBrokerName(), bd.getBrokerAddrs());
                        }
                        // Update Pub info
                        {
                            TopicPublishInfo publishInfo = topicRouteData2TopicPublishInfo(topic, topicRouteData);
                            publishInfo.setHaveTopicRouterInfo(true);
                            Iterator<Entry<String, MQProducerInner>> it = this.producerTable.entrySet().iterator();
                            while (it.hasNext()) {
                                Entry<String, MQProducerInner> entry = it.next();
                                MQProducerInner impl = entry.getValue();
                                if (impl != null) {
                                    // 更新topic的PublishInfo
                                    impl.updateTopicPublishInfo(topic, publishInfo);
                                }
                            }
                        }
                        // Update sub info
                        {
                            Set<MessageQueue> subscribeInfo = topicRouteData2TopicSubscribeInfo(topic, topicRouteData);
                            Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator();
                            while (it.hasNext()) {
                                Entry<String, MQConsumerInner> entry = it.next();
                                MQConsumerInner impl = entry.getValue();
                                if (impl != null) {
                                    impl.updateTopicSubscribeInfo(topic, subscribeInfo);
                                }
                            }
                        }
                        log.info("topicRouteTable.put. Topic = {}, TopicRouteData[{}]", topic, cloneTopicRouteData);
                        this.topicRouteTable.put(topic, cloneTopicRouteData);
                        return true;
                    }
                } else {
                    log.warn("updateTopicRouteInfoFromNameServer, getTopicRouteInfoFromNameServer return null, Topic: {}", topic);
                }
            } catch (Exception e) {
                if (!topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX) && !topic.equals(MixAll.DEFAULT_TOPIC)) {
                    log.warn("updateTopicRouteInfoFromNameServer Exception", e);
                }
            } finally {
                this.lockNamesrv.unlock();
            }
        } else {
            log.warn("updateTopicRouteInfoFromNameServer tryLock timeout {}ms", LOCK_TIMEOUT_MILLIS);
        }
    } catch (InterruptedException e) {
        log.warn("updateTopicRouteInfoFromNameServer Exception", e);
    }
    return false;
}
Also used : MQConsumerInner(org.apache.rocketmq.client.impl.consumer.MQConsumerInner) Set(java.util.Set) HashSet(java.util.HashSet) MQProducerInner(org.apache.rocketmq.client.impl.producer.MQProducerInner) BrokerData(org.apache.rocketmq.common.protocol.route.BrokerData) QueueData(org.apache.rocketmq.common.protocol.route.QueueData) MQClientException(org.apache.rocketmq.client.exception.MQClientException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException) TopicRouteData(org.apache.rocketmq.common.protocol.route.TopicRouteData) Entry(java.util.Map.Entry) TopicPublishInfo(org.apache.rocketmq.client.impl.producer.TopicPublishInfo) Iterator(java.util.Iterator)

Example 57 with TopicRouteData

use of org.apache.rocketmq.common.protocol.route.TopicRouteData in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MQClientInstance method uploadFilterClassToAllFilterServer.

private void uploadFilterClassToAllFilterServer(final String consumerGroup, final String fullClassName, final String topic, final String filterClassSource) throws UnsupportedEncodingException {
    byte[] classBody = null;
    int classCRC = 0;
    try {
        classBody = filterClassSource.getBytes(MixAll.DEFAULT_CHARSET);
        classCRC = UtilAll.crc32(classBody);
    } catch (Exception e1) {
        // 
        log.warn(// 
        "uploadFilterClassToAllFilterServer Exception, ClassName: {} {}", // 
        fullClassName, RemotingHelper.exceptionSimpleDesc(e1));
    }
    TopicRouteData topicRouteData = this.topicRouteTable.get(topic);
    if (// 
    topicRouteData != null && topicRouteData.getFilterServerTable() != null && !topicRouteData.getFilterServerTable().isEmpty()) {
        Iterator<Entry<String, List<String>>> it = topicRouteData.getFilterServerTable().entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, List<String>> next = it.next();
            List<String> value = next.getValue();
            for (final String fsAddr : value) {
                try {
                    this.mQClientAPIImpl.registerMessageFilterClass(fsAddr, consumerGroup, topic, fullClassName, classCRC, classBody, 5000);
                    log.info("register message class filter to {} OK, ConsumerGroup: {} Topic: {} ClassName: {}", fsAddr, consumerGroup, topic, fullClassName);
                } catch (Exception e) {
                    log.error("uploadFilterClassToAllFilterServer Exception", e);
                }
            }
        }
    } else {
        log.warn("register message class filter failed, because no filter server, ConsumerGroup: {} Topic: {} ClassName: {}", consumerGroup, topic, fullClassName);
    }
}
Also used : Entry(java.util.Map.Entry) List(java.util.List) MQClientException(org.apache.rocketmq.client.exception.MQClientException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException) TopicRouteData(org.apache.rocketmq.common.protocol.route.TopicRouteData)

Example 58 with TopicRouteData

use of org.apache.rocketmq.common.protocol.route.TopicRouteData in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MQClientInstance method findBrokerAddrByTopic.

public String findBrokerAddrByTopic(final String topic) {
    TopicRouteData topicRouteData = this.topicRouteTable.get(topic);
    if (topicRouteData != null) {
        List<BrokerData> brokers = topicRouteData.getBrokerDatas();
        if (!brokers.isEmpty()) {
            int index = random.nextInt(brokers.size());
            BrokerData bd = brokers.get(index % brokers.size());
            return bd.selectBrokerAddr();
        }
    }
    return null;
}
Also used : BrokerData(org.apache.rocketmq.common.protocol.route.BrokerData) TopicRouteData(org.apache.rocketmq.common.protocol.route.TopicRouteData)

Example 59 with TopicRouteData

use of org.apache.rocketmq.common.protocol.route.TopicRouteData in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MQClientInstance method isBrokerAddrExistInTopicRouteTable.

private boolean isBrokerAddrExistInTopicRouteTable(final String addr) {
    Iterator<Entry<String, TopicRouteData>> it = this.topicRouteTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, TopicRouteData> entry = it.next();
        TopicRouteData topicRouteData = entry.getValue();
        List<BrokerData> bds = topicRouteData.getBrokerDatas();
        for (BrokerData bd : bds) {
            if (bd.getBrokerAddrs() != null) {
                boolean exist = bd.getBrokerAddrs().containsValue(addr);
                if (exist)
                    return true;
            }
        }
    }
    return false;
}
Also used : Entry(java.util.Map.Entry) BrokerData(org.apache.rocketmq.common.protocol.route.BrokerData) TopicRouteData(org.apache.rocketmq.common.protocol.route.TopicRouteData)

Example 60 with TopicRouteData

use of org.apache.rocketmq.common.protocol.route.TopicRouteData in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MQAdminImpl method queryMessage.

/**
 * 通过断点查看rocketmq-console项目查询MessageId我们可以发现,只有offsetMsgId才是真正的这种规则的key,而msgId其实仅仅知识生成的UNIQ_KEY
 * 这也是为什么用MessageDecoder.decodeMessageId端口号超限问题的原因
 */
protected QueryResult queryMessage(String topic, String key, int maxNum, long begin, long end, boolean isUniqKey) throws MQClientException, InterruptedException {
    TopicRouteData topicRouteData = this.mQClientFactory.getAnExistTopicRouteData(topic);
    if (null == topicRouteData) {
        this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
        topicRouteData = this.mQClientFactory.getAnExistTopicRouteData(topic);
    }
    if (topicRouteData != null) {
        List<String> brokerAddrs = new LinkedList<String>();
        for (BrokerData brokerData : topicRouteData.getBrokerDatas()) {
            String addr = brokerData.selectBrokerAddr();
            if (addr != null) {
                brokerAddrs.add(addr);
            }
        }
        if (!brokerAddrs.isEmpty()) {
            final CountDownLatch countDownLatch = new CountDownLatch(brokerAddrs.size());
            final List<QueryResult> queryResultList = new LinkedList<QueryResult>();
            final ReadWriteLock lock = new ReentrantReadWriteLock(false);
            for (String addr : brokerAddrs) {
                try {
                    // 构建查询请求头信息
                    QueryMessageRequestHeader requestHeader = new QueryMessageRequestHeader();
                    requestHeader.setTopic(topic);
                    requestHeader.setKey(key);
                    requestHeader.setMaxNum(maxNum);
                    requestHeader.setBeginTimestamp(begin);
                    requestHeader.setEndTimestamp(end);
                    this.mQClientFactory.getMQClientAPIImpl().queryMessage(addr, requestHeader, timeoutMillis * 3, new InvokeCallback() {

                        @Override
                        public void operationComplete(ResponseFuture responseFuture) {
                            try {
                                RemotingCommand response = responseFuture.getResponseCommand();
                                if (response != null) {
                                    switch(response.getCode()) {
                                        case ResponseCode.SUCCESS:
                                            {
                                                QueryMessageResponseHeader responseHeader = null;
                                                try {
                                                    responseHeader = (QueryMessageResponseHeader) response.decodeCommandCustomHeader(QueryMessageResponseHeader.class);
                                                } catch (RemotingCommandException e) {
                                                    log.error("decodeCommandCustomHeader exception", e);
                                                    return;
                                                }
                                                List<MessageExt> wrappers = MessageDecoder.decodes(ByteBuffer.wrap(response.getBody()), true);
                                                QueryResult qr = new QueryResult(responseHeader.getIndexLastUpdateTimestamp(), wrappers);
                                                try {
                                                    lock.writeLock().lock();
                                                    queryResultList.add(qr);
                                                } finally {
                                                    lock.writeLock().unlock();
                                                }
                                                break;
                                            }
                                        default:
                                            log.warn("getResponseCommand failed, {} {}", response.getCode(), response.getRemark());
                                            break;
                                    }
                                } else {
                                    log.warn("getResponseCommand return null");
                                }
                            } finally {
                                countDownLatch.countDown();
                            }
                        }
                    }, isUniqKey);
                } catch (Exception e) {
                    log.warn("queryMessage exception", e);
                }
            }
            boolean ok = countDownLatch.await(timeoutMillis * 4, TimeUnit.MILLISECONDS);
            if (!ok) {
                log.warn("queryMessage, maybe some broker failed");
            }
            long indexLastUpdateTimestamp = 0;
            List<MessageExt> messageList = new LinkedList<MessageExt>();
            for (QueryResult qr : queryResultList) {
                if (qr.getIndexLastUpdateTimestamp() > indexLastUpdateTimestamp) {
                    indexLastUpdateTimestamp = qr.getIndexLastUpdateTimestamp();
                }
                for (MessageExt msgExt : qr.getMessageList()) {
                    if (isUniqKey) {
                        if (msgExt.getMsgId().equals(key)) {
                            if (messageList.size() > 0) {
                                if (messageList.get(0).getStoreTimestamp() > msgExt.getStoreTimestamp()) {
                                    messageList.clear();
                                    messageList.add(msgExt);
                                }
                            } else {
                                messageList.add(msgExt);
                            }
                        } else {
                            log.warn("queryMessage by uniqKey, find message key not matched, maybe hash duplicate {}", msgExt.toString());
                        }
                    } else {
                        String keys = msgExt.getKeys();
                        if (keys != null) {
                            boolean matched = false;
                            String[] keyArray = keys.split(MessageConst.KEY_SEPARATOR);
                            if (keyArray != null) {
                                for (String k : keyArray) {
                                    if (key.equals(k)) {
                                        matched = true;
                                        break;
                                    }
                                }
                            }
                            if (matched) {
                                messageList.add(msgExt);
                            } else {
                                log.warn("queryMessage, find message key not matched, maybe hash duplicate {}", msgExt.toString());
                            }
                        }
                    }
                }
            }
            if (!messageList.isEmpty()) {
                return new QueryResult(indexLastUpdateTimestamp, messageList);
            } else {
                throw new MQClientException(ResponseCode.NO_MESSAGE, "query message by key finished, but no message.");
            }
        }
    }
    throw new MQClientException(ResponseCode.TOPIC_NOT_EXIST, "The topic[" + topic + "] not matched route info");
}
Also used : InvokeCallback(org.apache.rocketmq.remoting.InvokeCallback) QueryMessageRequestHeader(org.apache.rocketmq.common.protocol.header.QueryMessageRequestHeader) BrokerData(org.apache.rocketmq.common.protocol.route.BrokerData) RemotingCommandException(org.apache.rocketmq.remoting.exception.RemotingCommandException) ResponseFuture(org.apache.rocketmq.remoting.netty.ResponseFuture) CountDownLatch(java.util.concurrent.CountDownLatch) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) LinkedList(java.util.LinkedList) RemotingCommandException(org.apache.rocketmq.remoting.exception.RemotingCommandException) 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) RemotingCommand(org.apache.rocketmq.remoting.protocol.RemotingCommand) MessageExt(org.apache.rocketmq.common.message.MessageExt) QueryResult(org.apache.rocketmq.client.QueryResult) QueryMessageResponseHeader(org.apache.rocketmq.common.protocol.header.QueryMessageResponseHeader) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) MQClientException(org.apache.rocketmq.client.exception.MQClientException)

Aggregations

TopicRouteData (org.apache.rocketmq.common.protocol.route.TopicRouteData)92 BrokerData (org.apache.rocketmq.common.protocol.route.BrokerData)65 ArrayList (java.util.ArrayList)25 MQClientException (org.apache.rocketmq.client.exception.MQClientException)25 QueueData (org.apache.rocketmq.common.protocol.route.QueueData)25 HashMap (java.util.HashMap)22 DefaultMQAdminExt (org.apache.rocketmq.tools.admin.DefaultMQAdminExt)20 MessageQueue (org.apache.rocketmq.common.message.MessageQueue)18 List (java.util.List)16 HashSet (java.util.HashSet)13 Entry (java.util.Map.Entry)12 ConsumeStats (org.apache.rocketmq.common.admin.ConsumeStats)12 ArgumentMatchers.anyLong (org.mockito.ArgumentMatchers.anyLong)12 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)12 RemotingException (org.apache.rocketmq.remoting.exception.RemotingException)11 Field (java.lang.reflect.Field)10 MQBrokerException (org.apache.rocketmq.client.exception.MQBrokerException)10 MQClientAPIImpl (org.apache.rocketmq.client.impl.MQClientAPIImpl)10 MQClientInstance (org.apache.rocketmq.client.impl.factory.MQClientInstance)10 DefaultMQAdminExtImpl (org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl)10