com.alibaba.rocketmq.common.UtilAll Java Examples

The following examples show how to use com.alibaba.rocketmq.common.UtilAll. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StoreCheckpoint.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public StoreCheckpoint(final String scpPath) throws IOException {
    File file = new File(scpPath);
    MapedFile.ensureDirOK(file.getParent());
    boolean fileExists = file.exists();

    this.randomAccessFile = new RandomAccessFile(file, "rw");
    this.fileChannel = this.randomAccessFile.getChannel();
    this.mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, MapedFile.OS_PAGE_SIZE);

    if (fileExists) {
        log.info("store checkpoint file exists, " + scpPath);
        this.physicMsgTimestamp = this.mappedByteBuffer.getLong(0);
        this.logicsMsgTimestamp = this.mappedByteBuffer.getLong(8);
        this.indexMsgTimestamp = this.mappedByteBuffer.getLong(16);

        log.info("store checkpoint file physicMsgTimestamp " + this.physicMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.physicMsgTimestamp));
        log.info("store checkpoint file logicsMsgTimestamp " + this.logicsMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.logicsMsgTimestamp));
        log.info("store checkpoint file indexMsgTimestamp " + this.indexMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.indexMsgTimestamp));
    } else {
        log.info("store checkpoint file not exists, " + scpPath);
    }
}
 
Example #2
Source File: MapedFile.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public boolean destroy(final long intervalForcibly) {
    this.shutdown(intervalForcibly);

    if (this.isCleanupOver()) {
        try {
            this.fileChannel.close();
            log.info("close file channel " + this.fileName + " OK");

            long beginTime = System.currentTimeMillis();
            boolean result = this.file.delete();
            log.info("delete file[REF:" + this.getRefCount() + "] " + this.fileName
                    + (result ? " OK, " : " Failed, ") + "W:" + this.getWrotePostion() + " M:"
                    + this.getCommittedPosition() + ", "
                    + UtilAll.computeEclipseTimeMilliseconds(beginTime));
        } catch (Exception e) {
            log.warn("close file channel " + this.fileName + " Failed. ", e);
        }

        return true;
    } else {
        log.warn("destroy maped file[REF:" + this.getRefCount() + "] " + this.fileName
                + " Failed. cleanupOver: " + this.cleanupOver);
    }

    return false;
}
 
Example #3
Source File: StoreCheckpoint.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 6 votes vote down vote up
public StoreCheckpoint(final String scpPath) throws IOException {
    File file = new File(scpPath);
    MapedFile.ensureDirOK(file.getParent());
    boolean fileExists = file.exists();

    this.randomAccessFile = new RandomAccessFile(file, "rw");
    this.fileChannel = this.randomAccessFile.getChannel();
    this.mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, MapedFile.OS_PAGE_SIZE);

    if (fileExists) {
        log.info("store checkpoint file exists, " + scpPath);
        this.physicMsgTimestamp = this.mappedByteBuffer.getLong(0);
        this.logicsMsgTimestamp = this.mappedByteBuffer.getLong(8);
        this.indexMsgTimestamp = this.mappedByteBuffer.getLong(16);

        log.info("store checkpoint file physicMsgTimestamp " + this.physicMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.physicMsgTimestamp));
        log.info("store checkpoint file logicsMsgTimestamp " + this.logicsMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.logicsMsgTimestamp));
        log.info("store checkpoint file indexMsgTimestamp " + this.indexMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.indexMsgTimestamp));
    }
    else {
        log.info("store checkpoint file not exists, " + scpPath);
    }
}
 
Example #4
Source File: Validators.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
/**
 * Validate topic
 *
 * @param topic
 *
 * @throws com.alibaba.rocketmq.client.exception.MQClientException
 */
public static void checkTopic(String topic) throws MQClientException {
    if (UtilAll.isBlank(topic)) {
        throw new MQClientException("the specified topic is blank", null);
    }

    if (!regularExpressionMatcher(topic, PATTERN)) {
        throw new MQClientException(String.format(
                "the specified topic[%s] contains illegal characters, allowing only %s", topic,
                VALID_PATTERN_STR), null);
    }

    if (topic.length() > CHARACTER_MAX_LENGTH) {
        throw new MQClientException("the specified topic is longer than topic max length 255.", null);
    }

    //whether the same with system reserved keyword
    if (topic.equals(MixAll.DEFAULT_TOPIC)) {
        throw new MQClientException(
                String.format("the topic[%s] is conflict with default topic.", topic), null);
    }
}
 
Example #5
Source File: ClientRemotingProcessor.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 6 votes vote down vote up
private RemotingCommand getConsumerRunningInfo(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final GetConsumerRunningInfoRequestHeader requestHeader =
            (GetConsumerRunningInfoRequestHeader) request.decodeCommandCustomHeader(GetConsumerRunningInfoRequestHeader.class);

    ConsumerRunningInfo consumerRunningInfo = this.mqClientFactory.consumerRunningInfo(requestHeader.getConsumerGroup());
    if (null != consumerRunningInfo) {
        if (requestHeader.isJstackEnable()) {
            Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
            consumerRunningInfo.setStackTraceElementMap(map);
            String jstack = UtilAll.jstack(map);
            consumerRunningInfo.setJstack(jstack);
        }

        response.setCode(ResponseCode.SUCCESS);
        response.setBody(consumerRunningInfo.encode());
    }
    else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark(String.format("The Consumer Group <%s> not exist in this consumer", requestHeader.getConsumerGroup()));
    }

    return response;
}
 
Example #6
Source File: ConsumeMessageOrderlyService.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public boolean sendMessageBack(final MessageExt msg) {
    try {
        Message newMsg = new Message(MixAll.getRetryTopic(this.defaultMQPushConsumer.getConsumerGroup()), msg.getBody());
        String originMsgId = MessageAccessor.getOriginMessageId(msg);
        MessageAccessor.setOriginMessageId(newMsg, UtilAll.isBlank(originMsgId) ? msg.getMsgId() : originMsgId);
        newMsg.setFlag(msg.getFlag());
        MessageAccessor.setProperties(newMsg, msg.getProperties());
        MessageAccessor.putProperty(newMsg, MessageConst.PROPERTY_RETRY_TOPIC, msg.getTopic());
        MessageAccessor.setReconsumeTime(newMsg, String.valueOf(msg.getReconsumeTimes()));
        MessageAccessor.setMaxReconsumeTimes(newMsg, String.valueOf(this.defaultMQPushConsumer.getMaxReconsumeTimes()));
        newMsg.setDelayTimeLevel(3 + msg.getReconsumeTimes());

        this.defaultMQPushConsumer.getDefaultMQPushConsumerImpl().getmQClientFactory().getDefaultMQProducer().send(newMsg);
        return true;
    } catch (Exception e) {
        log.error("sendMessageBack exception, group: " + this.consumerGroup + " msg: " + msg.toString(), e);
    }

    return false;
}
 
Example #7
Source File: DefaultMQProducerImpl.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 6 votes vote down vote up
private boolean tryToCompressMessage(final Message msg) {
    byte[] body = msg.getBody();
    if (body != null) {
        if (body.length >= this.defaultMQProducer.getCompressMsgBodyOverHowmuch()) {
            try {
                byte[] data = UtilAll.compress(body, zipCompressLevel);
                if (data != null) {
                    msg.setBody(data);
                    return true;
                }
            }
            catch (IOException e) {
                log.error("tryToCompressMessage exception", e);
                log.warn(msg.toString());
            }
        }
    }

    return false;
}
 
Example #8
Source File: StoreCheckpoint.java    From RocketMQ-Master-analyze with Apache License 2.0 6 votes vote down vote up
public StoreCheckpoint(final String scpPath) throws IOException {
    File file = new File(scpPath);
    MapedFile.ensureDirOK(file.getParent());
    boolean fileExists = file.exists();

    this.randomAccessFile = new RandomAccessFile(file, "rw");
    this.fileChannel = this.randomAccessFile.getChannel();
    this.mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, MapedFile.OS_PAGE_SIZE);

    if (fileExists) {
        log.info("store checkpoint file exists, " + scpPath);
        this.physicMsgTimestamp = this.mappedByteBuffer.getLong(0);
        this.logicsMsgTimestamp = this.mappedByteBuffer.getLong(8);
        this.indexMsgTimestamp = this.mappedByteBuffer.getLong(16);

        log.info("store checkpoint file physicMsgTimestamp " + this.physicMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.physicMsgTimestamp));
        log.info("store checkpoint file logicsMsgTimestamp " + this.logicsMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.logicsMsgTimestamp));
        log.info("store checkpoint file indexMsgTimestamp " + this.indexMsgTimestamp + ", "
                + UtilAll.timeMillisToHumanString(this.indexMsgTimestamp));
    }
    else {
        log.info("store checkpoint file not exists, " + scpPath);
    }
}
 
Example #9
Source File: MomentStatsItem.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
public void init() {
    // 分钟整点执行
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                printAtMinutes();
            }
            catch (Throwable e) {
            }
        }
    }, Math.abs(UtilAll.computNextMinutesTimeMillis() - System.currentTimeMillis()), //
        1000 * 60 * 5, TimeUnit.MILLISECONDS);
}
 
Example #10
Source File: FilterClassManager.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
private void fetchClassFromRemoteHost() {
    Iterator<Entry<String, FilterClassInfo>> it = this.filterClassTable.entrySet().iterator();
    while (it.hasNext()) {
        try {
            Entry<String, FilterClassInfo> next = it.next();
            FilterClassInfo filterClassInfo = next.getValue();
            String[] topicAndGroup = next.getKey().split("@");
            String responseStr = this.filterClassFetchMethod.fetch(topicAndGroup[0], topicAndGroup[1],
                filterClassInfo.getClassName());
            byte[] filterSourceBinary = responseStr.getBytes("UTF-8");
            int classCRC = UtilAll.crc32(responseStr.getBytes("UTF-8"));
            if (classCRC != filterClassInfo.getClassCRC()) {
                String javaSource = new String(filterSourceBinary, MixAll.DEFAULT_CHARSET);
                Class<?> newClass =
                        DynaCode.compileAndLoadClass(filterClassInfo.getClassName(), javaSource);
                Object newInstance = newClass.newInstance();
                filterClassInfo.setMessageFilter((MessageFilter) newInstance);
                filterClassInfo.setClassCRC(classCRC);

                log.info("fetch Remote class File OK, {} {}", next.getKey(),
                    filterClassInfo.getClassName());
            }
        }
        catch (Exception e) {
            log.error("fetchClassFromRemoteHost Exception", e);
        }
    }
}
 
Example #11
Source File: CommitLog.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
private boolean isMapedFileMatchedRecover(final MapedFile mapedFile) {
    ByteBuffer byteBuffer = mapedFile.sliceByteBuffer();

    int magicCode = byteBuffer.getInt(MessageDecoder.MessageMagicCodePostion);
    if (magicCode != MessageMagicCode) {
        return false;
    }

    long storeTimestamp = byteBuffer.getLong(MessageDecoder.MessageStoreTimestampPostion);
    if (0 == storeTimestamp) {
        return false;
    }

    if (this.defaultMessageStore.getMessageStoreConfig().isMessageIndexEnable()//
            && this.defaultMessageStore.getMessageStoreConfig().isMessageIndexSafe()) {
        if (storeTimestamp <= this.defaultMessageStore.getStoreCheckpoint().getMinTimestampIndex()) {
            log.info("find check timestamp, {} {}", //
                storeTimestamp,//
                UtilAll.timeMillisToHumanString(storeTimestamp));
            return true;
        }
    }
    else {
        if (storeTimestamp <= this.defaultMessageStore.getStoreCheckpoint().getMinTimestamp()) {
            log.info("find check timestamp, {} {}", //
                storeTimestamp,//
                UtilAll.timeMillisToHumanString(storeTimestamp));
            return true;
        }
    }

    return false;
}
 
Example #12
Source File: SendResult.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
public SendResult(SendStatus sendStatus, String msgId, MessageQueue messageQueue, long queueOffset,
        String projectGroupPrefix) {
    this.sendStatus = sendStatus;
    this.msgId = msgId;
    this.messageQueue = messageQueue;
    this.queueOffset = queueOffset;
    if (!UtilAll.isBlank(projectGroupPrefix)) {
        this.messageQueue
            .setTopic(VirtualEnvUtil.clearProjectGroup(this.messageQueue.getTopic(), projectGroupPrefix));
    }
}
 
Example #13
Source File: MapedFile.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
public boolean destroy(final long intervalForcibly) {
    this.shutdown(intervalForcibly);

    if (this.isCleanupOver()) {
        try {
            this.fileChannel.close();
            log.info("close file channel " + this.fileName + " OK");

            long beginTime = System.currentTimeMillis();
            boolean result = this.file.delete();
            log.info("delete file[REF:" + this.getRefCount() + "] " + this.fileName
                    + (result ? " OK, " : " Failed, ") + "W:" + this.getWrotePostion() + " M:"
                    + this.getCommittedPosition() + ", "
                    + UtilAll.computeEclipseTimeMilliseconds(beginTime));
        }
        catch (Exception e) {
            log.warn("close file channel " + this.fileName + " Failed. ", e);
        }

        return true;
    }
    else {
        log.warn("destroy maped file[REF:" + this.getRefCount() + "] " + this.fileName
                + " Failed. cleanupOver: " + this.cleanupOver);
    }

    return false;
}
 
Example #14
Source File: MessageDecoder.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
public static String createMessageId(SocketAddress socketAddress, long transactionIdhashCode) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(MessageDecoder.MSG_ID_LENGTH);
    InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
    byteBuffer.put(inetSocketAddress.getAddress().getAddress());
    byteBuffer.putInt(inetSocketAddress.getPort());
    byteBuffer.putLong(transactionIdhashCode);
    byteBuffer.flip();
    return UtilAll.bytes2string(byteBuffer.array());
}
 
Example #15
Source File: PrintMessageSubCommand.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static long timestampFormat(final String value) {
    long timestamp = 0;
    try {
        timestamp = Long.parseLong(value);
    } catch (NumberFormatException e) {

        timestamp = UtilAll.parseDate(value, UtilAll.yyyy_MM_dd_HH_mm_ss_SSS).getTime();
    }

    return timestamp;
}
 
Example #16
Source File: MessageDecoder.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static String createMessageId(final ByteBuffer input, final ByteBuffer addr, final long offset) {
    input.flip();
    input.limit(MessageDecoder.MSG_ID_LENGTH);

    input.put(addr);
    input.putLong(offset);

    return UtilAll.bytes2string(input.array());
}
 
Example #17
Source File: CommitLog.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
private boolean isMapedFileMatchedRecover(final MapedFile mapedFile) {
    ByteBuffer byteBuffer = mapedFile.sliceByteBuffer();

    int magicCode = byteBuffer.getInt(MessageDecoder.MessageMagicCodePostion);
    if (magicCode != MessageMagicCode) {
        return false;
    }

    long storeTimestamp = byteBuffer.getLong(MessageDecoder.MessageStoreTimestampPostion);
    if (0 == storeTimestamp) {
        return false;
    }

    if (this.defaultMessageStore.getMessageStoreConfig().isMessageIndexEnable()//
            && this.defaultMessageStore.getMessageStoreConfig().isMessageIndexSafe()) {
        if (storeTimestamp <= this.defaultMessageStore.getStoreCheckpoint().getMinTimestampIndex()) {
            log.info("find check timestamp, {} {}", //
                    storeTimestamp, //
                    UtilAll.timeMillisToHumanString(storeTimestamp));
            return true;
        }
    } else {
        if (storeTimestamp <= this.defaultMessageStore.getStoreCheckpoint().getMinTimestamp()) {
            log.info("find check timestamp, {} {}", //
                    storeTimestamp, //
                    UtilAll.timeMillisToHumanString(storeTimestamp));
            return true;
        }
    }

    return false;
}
 
Example #18
Source File: ClientConfig.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 默认clientip + pid 做clientid .如果是单元模式,则加上 unitname.  通过这个来标识客户端
 * @return
 */
public String buildMQClientId() {
    StringBuilder sb = new StringBuilder();
    sb.append(this.getClientIP());

    sb.append("@");
    sb.append(this.getInstanceName());
    if(!UtilAll.isBlank(this.unitName)) {
        sb.append("@");
        sb.append(this.unitName);
    }

    return sb.toString();
}
 
Example #19
Source File: MomentStatsItem.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
public void init() {
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                printAtMinutes();
            }
            catch (Throwable e) {
            }
        }
    }, Math.abs(UtilAll.computNextMinutesTimeMillis() - System.currentTimeMillis()), //
        1000 * 60 * 5, TimeUnit.MILLISECONDS);
}
 
Example #20
Source File: MomentStatsItemSet.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
public void init() {
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                printAtMinutes();
            }
            catch (Throwable e) {
            }
        }
    }, Math.abs(UtilAll.computNextMinutesTimeMillis() - System.currentTimeMillis()), //
        1000 * 60 * 5, TimeUnit.MILLISECONDS);
}
 
Example #21
Source File: MQClientAPIImpl.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
/**
 * 获取producer连接信息
 * 
 * @param addr
 * @param producerGroup
 * @param timeoutMillis
 * @return
 * @throws RemotingConnectException
 * @throws RemotingSendRequestException
 * @throws RemotingTimeoutException
 * @throws InterruptedException
 * @throws MQBrokerException
 */
public ProducerConnection getProducerConnectionList(final String addr, final String producerGroup,
        final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException,
                RemotingTimeoutException, InterruptedException, MQBrokerException {
    String producerGroupWithProjectGroup = producerGroup;
    if (!UtilAll.isBlank(projectGroupPrefix)) {
        producerGroupWithProjectGroup =
                VirtualEnvUtil.buildWithProjectGroup(producerGroup, projectGroupPrefix);
    }

    GetProducerConnectionListRequestHeader requestHeader = new GetProducerConnectionListRequestHeader();
    requestHeader.setProducerGroup(producerGroupWithProjectGroup);

    RemotingCommand request =
            RemotingCommand.createRequestCommand(RequestCode.GET_PRODUCER_CONNECTION_LIST, requestHeader);

    RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
    switch (response.getCode()) {
    case ResponseCode.SUCCESS: {
        return ProducerConnection.decode(response.getBody(), ProducerConnection.class);
    }
    default:
        break;
    }

    throw new MQBrokerException(response.getCode(), response.getRemark());
}
 
Example #22
Source File: VirtualEnvUtil.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
/**
 * @param origin
 * @param projectGroup
 * @return
 */
public static String buildWithProjectGroup(String origin, String projectGroup) {
    if (!UtilAll.isBlank(projectGroup)) {
        String prefix = String.format(VIRTUAL_APPGROUP_PREFIX, projectGroup);
        if (!origin.endsWith(prefix)) {
            return origin + prefix;
        } else {
            return origin;
        }
    } else {
        return origin;
    }
}
 
Example #23
Source File: VirtualEnvUtil.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
/**
 * @param origin
 * @param projectGroup
 * @return
 */
public static String clearProjectGroup(String origin, String projectGroup) {
    String prefix = String.format(VIRTUAL_APPGROUP_PREFIX, projectGroup);
    if (!UtilAll.isBlank(prefix) && origin.endsWith(prefix)) {
        return origin.substring(0, origin.lastIndexOf(prefix));
    } else {
        return origin;
    }
}
 
Example #24
Source File: DefaultMQPushConsumerImpl.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
public void sendMessageBack(MessageExt msg, int delayLevel, final String brokerName)
        throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    try {
        String brokerAddr =
                (null != brokerName) ? this.mQClientFactory.findBrokerAddressInPublish(brokerName)
                        : RemotingHelper.parseSocketAddressAddr(msg.getStoreHost());

        this.mQClientFactory.getMQClientAPIImpl().consumerSendMessageBack(brokerAddr, msg,
            this.defaultMQPushConsumer.getConsumerGroup(), delayLevel, 5000);
    }
    catch (Exception e) {
        log.error("sendMessageBack Exception, " + this.defaultMQPushConsumer.getConsumerGroup(), e);

        Message newMsg = new Message(MixAll.getRetryTopic(this.defaultMQPushConsumer.getConsumerGroup()),
            msg.getBody());

        String originMsgId = MessageAccessor.getOriginMessageId(msg);
        MessageAccessor.setOriginMessageId(newMsg,
            UtilAll.isBlank(originMsgId) ? msg.getMsgId() : originMsgId);

        newMsg.setFlag(msg.getFlag());
        MessageAccessor.setProperties(newMsg, msg.getProperties());
        MessageAccessor.putProperty(newMsg, MessageConst.PROPERTY_RETRY_TOPIC, msg.getTopic());
        int reTimes = msg.getReconsumeTimes() + 1;
        MessageAccessor.setReconsumeTime(newMsg, reTimes + "");
        newMsg.setDelayTimeLevel(3 + reTimes);

        this.mQClientFactory.getDefaultMQProducer().send(newMsg);
    }
}
 
Example #25
Source File: Validators.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
/**
 * Validate group
 *
 * @param group
 *
 * @throws com.alibaba.rocketmq.client.exception.MQClientException
 */
public static void checkGroup(String group) throws MQClientException {
    if (UtilAll.isBlank(group)) {
        throw new MQClientException("the specified group is blank", null);
    }
    if (!regularExpressionMatcher(group, PATTERN)) {
        throw new MQClientException(String.format(
                "the specified group[%s] contains illegal characters, allowing only %s", group,
                VALID_PATTERN_STR), null);
    }
    if (group.length() > CHARACTER_MAX_LENGTH) {
        throw new MQClientException("the specified group is longer than group max length 255.", null);
    }
}
 
Example #26
Source File: VirtualEnvUtil.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
/**
 * @param origin
 * @param projectGroup
 * @return
 */
public static String buildWithProjectGroup(String origin, String projectGroup) {
    if (!UtilAll.isBlank(projectGroup)) {
        String prefix = String.format(VIRTUAL_APPGROUP_PREFIX, projectGroup);
        if (!origin.endsWith(prefix)) {
            return origin + prefix;
        }
        else {
            return origin;
        }
    }
    else {
        return origin;
    }
}
 
Example #27
Source File: MQClientAPIImpl.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
/**
 * Commit或者Rollback事务
 * 
 * @param addr
 * @param requestHeader
 * @param remark
 * @param timeoutMillis
 * @throws RemotingException
 * @throws MQBrokerException
 * @throws InterruptedException
 */
public void endTransactionOneway(final String addr, final EndTransactionRequestHeader requestHeader,
        final String remark, final long timeoutMillis)
                throws RemotingException, MQBrokerException, InterruptedException {
    if (!UtilAll.isBlank(projectGroupPrefix)) {
        requestHeader.setProducerGroup(
            VirtualEnvUtil.buildWithProjectGroup(requestHeader.getProducerGroup(), projectGroupPrefix));
    }

    RemotingCommand request =
            RemotingCommand.createRequestCommand(RequestCode.END_TRANSACTION, requestHeader);

    request.setRemark(remark);
    this.remotingClient.invokeOneway(addr, request, timeoutMillis);
}
 
Example #28
Source File: DefaultMQPullConsumerImpl.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public void sendMessageBack(MessageExt msg, int delayLevel, final String brokerName, String consumerGroup)
        throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    try {
        String brokerAddr = (null != brokerName) ? this.mQClientFactory.findBrokerAddressInPublish(brokerName)
                : RemotingHelper.parseSocketAddressAddr(msg.getStoreHost());

        if (UtilAll.isBlank(consumerGroup)) {
            consumerGroup = this.defaultMQPullConsumer.getConsumerGroup();
        }

        this.mQClientFactory.getMQClientAPIImpl().consumerSendMessageBack(brokerAddr, msg, consumerGroup, delayLevel, 3000,
                this.defaultMQPullConsumer.getMaxReconsumeTimes());
    } catch (Exception e) {
        log.error("sendMessageBack Exception, " + this.defaultMQPullConsumer.getConsumerGroup(), e);

        Message newMsg = new Message(MixAll.getRetryTopic(this.defaultMQPullConsumer.getConsumerGroup()), msg.getBody());
        String originMsgId = MessageAccessor.getOriginMessageId(msg);
        MessageAccessor.setOriginMessageId(newMsg, UtilAll.isBlank(originMsgId) ? msg.getMsgId() : originMsgId);
        newMsg.setFlag(msg.getFlag());
        MessageAccessor.setProperties(newMsg, msg.getProperties());
        MessageAccessor.putProperty(newMsg, MessageConst.PROPERTY_RETRY_TOPIC, msg.getTopic());
        MessageAccessor.setReconsumeTime(newMsg, String.valueOf(msg.getReconsumeTimes() + 1));
        MessageAccessor.setMaxReconsumeTimes(newMsg, String.valueOf(this.defaultMQPullConsumer.getMaxReconsumeTimes()));
        newMsg.setDelayTimeLevel(3 + msg.getReconsumeTimes());
        this.mQClientFactory.getDefaultMQProducer().send(newMsg);
    }
}
 
Example #29
Source File: MomentStatsItem.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public void init() {

        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
                                                              @Override
                                                              public void run() {
                                                                  try {
                                                                      printAtMinutes();

                                                                      MomentStatsItem.this.value.set(0);
                                                                  } catch (Throwable e) {
                                                                  }
                                                              }
                                                          }, Math.abs(UtilAll.computNextMinutesTimeMillis() - System.currentTimeMillis()), //
                1000 * 60 * 5, TimeUnit.MILLISECONDS);
    }
 
Example #30
Source File: MQClientInstance.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
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);
    }
}