org.apache.rocketmq.client.exception.MQClientException Java Examples

The following examples show how to use org.apache.rocketmq.client.exception.MQClientException. 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: RocketMQProducerTemplate.java    From rocketmq-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public void send(MessageProxy messageProxy) throws MQClientException, InterruptedException, RemotingException {
    SendCallback sendCallback = messageProxy.getSendCallback() == null ? new DefaultSendCallback() : messageProxy
            .getSendCallback();
    if (messageProxy.getMessage() == null) {
        throw new NullPointerException("the message is null");
    }
    if (this.isOrderlyMessage()) {
        MessageQueueSelector selector = messageProxy.getMessageQueueSelector();
        if (selector == null) {
            throw new NullPointerException("the sequential message must be configured with MessageQueueSelector.");
        }
        this.defaultMQProducer.send(messageProxy.getMessage(), selector, messageProxy.getSelectorArg(),
                sendCallback);
    } else {
        this.defaultMQProducer.send(messageProxy.getMessage(), sendCallback);
    }
}
 
Example #2
Source File: OrderStatusUpdateProducer.java    From order-charge-notify with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    // 初始化回查线程池
    executorService = new ThreadPoolExecutor(
            5,
            512,
            10000L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(512),
            runnable -> {
                Thread thread = new Thread(runnable);
                thread.setName(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getProducerGroup() + "-check-thread");
                return null;
            });

    transactionMQProducer = new TransactionMQProducer(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getProducerGroup());
    transactionMQProducer.setNamesrvAddr(nameSrvAddr);
    transactionMQProducer.setExecutorService(executorService);
    transactionMQProducer.setTransactionListener(transactionListener);
    try {
        transactionMQProducer.start();
    } catch (MQClientException e) {
        throw new RuntimeException("启动[订单状态修改生产者]OrderStatusUpdateProducer异常", e);
    }
    LOGGER.info("启动[订单状态修改生产者]OrderStatusUpdateProducer成功, topic={}", MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getTopic());
}
 
Example #3
Source File: DefaultMQAdminExtImpl.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
@Override
public ConsumerConnection examineConsumerConnectionInfo(
    String consumerGroup) throws InterruptedException, MQBrokerException,
    RemotingException, MQClientException {
    ConsumerConnection result = new ConsumerConnection();
    String topic = MixAll.getRetryTopic(consumerGroup);
    List<BrokerData> brokers = this.examineTopicRouteInfo(topic).getBrokerDatas();
    BrokerData brokerData = brokers.get(random.nextInt(brokers.size()));
    String addr = null;
    if (brokerData != null) {
        addr = brokerData.selectBrokerAddr();
        if (StringUtils.isNotBlank(addr)) {
            result = this.mqClientInstance.getMQClientAPIImpl().getConsumerConnectionList(addr, consumerGroup, timeoutMillis);
        }
    }

    if (result.getConnectionSet().isEmpty()) {
        log.warn("the consumer group not online. brokerAddr={}, group={}", addr, consumerGroup);
        throw new MQClientException(ResponseCode.CONSUMER_NOT_ONLINE, "Not found the consumer group connection");
    }

    return result;
}
 
Example #4
Source File: DefaultMQProducerTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMessageAsync_Success() throws RemotingException, InterruptedException, MQBrokerException, MQClientException {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
    producer.send(message, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
            assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
            assertThat(sendResult.getQueueOffset()).isEqualTo(456L);
            countDownLatch.countDown();
        }

        @Override
        public void onException(Throwable e) {
            countDownLatch.countDown();
        }
    });
    countDownLatch.await(3000L, TimeUnit.MILLISECONDS);
}
 
Example #5
Source File: Utils.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private static DefaultMQProducer getSendCheckProducer(String nameSvr, String cluster, String broker) {
    String key = cluster + "_" + nameSvr + "_" + broker;
    return brokerSendCheckMap.computeIfAbsent(key, s -> {
        try {
            DefaultMQProducer producer = new DefaultMQProducer("monitor_pusher_" + key.replaceAll(":", "_").replaceAll("\\.", "_"));
            producer.setNamesrvAddr(nameSvr);
            producer.setVipChannelEnabled(false);
            producer.setInstanceName(String.valueOf(System.currentTimeMillis()));
            producer.start();
            return producer;
        } catch (MQClientException e) {
            logger.error("[DefaultMQProducer] start mqAdminExt error, nameServer:{}, cluster:{} broker:{}", nameSvr, cluster, broker, e);
            throw new RuntimeException("[DefaultMQProducer] start mqAdminExt error, nameServer:" + nameSvr);
        }
    });
}
 
Example #6
Source File: SendMsgStatusCommandTest.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
    mQClientAPIImpl = mock(MQClientAPIImpl.class);
    defaultMQAdminExt = new DefaultMQAdminExt();
    defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);

    Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
    field.setAccessible(true);
    field.set(defaultMQAdminExtImpl, mqClientInstance);
    field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    field.setAccessible(true);
    field.set(mqClientInstance, mQClientAPIImpl);
    field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
    field.setAccessible(true);
    field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
}
 
Example #7
Source File: MQClientAPIImpl.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public boolean cleanUnusedTopicByAddr(final String addr,
    long timeoutMillis) throws MQClientException, RemotingConnectException,
    RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_UNUSED_TOPIC, null);
    RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
        request, timeoutMillis);
    switch (response.getCode()) {
        case ResponseCode.SUCCESS: {
            return true;
        }
        default:
            break;
    }

    throw new MQClientException(response.getCode(), response.getRemark());
}
 
Example #8
Source File: DefaultMQAdminExtImpl.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
@Override
public TopicStatsTable examineTopicStats(String topic) throws RemotingException, MQClientException, InterruptedException,
    MQBrokerException {
    TopicRouteData topicRouteData = this.examineTopicRouteInfo(topic);
    TopicStatsTable topicStatsTable = new TopicStatsTable();

    for (BrokerData bd : topicRouteData.getBrokerDatas()) {
        String addr = bd.selectBrokerAddr();
        if (addr != null) {
            TopicStatsTable tst = this.mqClientInstance.getMQClientAPIImpl().getTopicStatsInfo(addr, topic, timeoutMillis);
            topicStatsTable.getOffsetTable().putAll(tst.getOffsetTable());
        }
    }

    if (topicStatsTable.getOffsetTable().isEmpty()) {
        throw new MQClientException("Not found the topic stats info", null);
    }

    return topicStatsTable;
}
 
Example #9
Source File: RMQAsyncSendProducer.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
private void start() {
    try {
        producer.start();
    } catch (MQClientException e) {
        logger.error("producer start failed!");
        e.printStackTrace();
    }
}
 
Example #10
Source File: DefaultMQPushConsumerImpl.java    From DDMQ 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 {
    if (MixAll.MQTT_MODE) {
        log.error("send MessageBack in MQTT MODE is illegal, msg={}, brokerName={}", msg, brokerName);
        return;
    }
    try {
        String brokerAddr = (null != brokerName) ? this.mQClientFactory.findBrokerAddressInPublish(brokerName)
            : RemotingHelper.parseSocketAddressAddr(msg.getStoreHost());
        this.mQClientFactory.getMQClientAPIImpl().consumerSendMessageBack(brokerAddr, msg,
            this.defaultMQPushConsumer.getConsumerGroup(), delayLevel, 5000, getMaxReconsumeTimes());
    } 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());
        MessageAccessor.setReconsumeTime(newMsg, String.valueOf(msg.getReconsumeTimes() + 1));
        MessageAccessor.setMaxReconsumeTimes(newMsg, String.valueOf(getMaxReconsumeTimes()));
        newMsg.setDelayTimeLevel(3 + msg.getReconsumeTimes());

        this.mQClientFactory.getDefaultMQProducer().send(newMsg);
    }
}
 
Example #11
Source File: TransactionProducer.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    TransactionCheckListener transactionCheckListener = new TransactionCheckListenerImpl();
    TransactionMQProducer producer = new TransactionMQProducer("please_rename_unique_group_name");
    producer.setCheckThreadPoolMinSize(2);
    producer.setCheckThreadPoolMaxSize(2);
    producer.setCheckRequestHoldMax(2000);
    producer.setTransactionCheckListener(transactionCheckListener);
    producer.start();

    String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};
    TransactionExecuterImpl tranExecuter = new TransactionExecuterImpl();
    for (int i = 0; i < 100; i++) {
        try {
            Message msg =
                new Message("TopicTest", tags[i % tags.length], "KEY" + i,
                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.sendMessageInTransaction(msg, tranExecuter, null);
            System.out.printf("%s%n", sendResult);

            Thread.sleep(10);
        } catch (MQClientException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    for (int i = 0; i < 100000; i++) {
        Thread.sleep(1000);
    }
    producer.shutdown();
}
 
Example #12
Source File: RmqAdminServiceImpl.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private DefaultMQAdminExt getMQAdminExt(String addr) {
    return mqAdminExtMap.computeIfAbsent(addr, s -> {
        try {
            DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt();
            defaultMQAdminExt.setNamesrvAddr(addr);
            defaultMQAdminExt.setInstanceName(String.valueOf(System.currentTimeMillis()));
            defaultMQAdminExt.start();
            return defaultMQAdminExt;
        } catch (MQClientException e) {
            LOGGER.error("[RMQ] start mqadminext error, nameServer:" + addr, e);
            throw new RuntimeException("[RMQ] start mqAdminExt error, nameServer:" + addr);
        }
    });
}
 
Example #13
Source File: DefaultMQProducerImpl.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
/**
 * KERNEL ONEWAY -------------------------------------------------------
 */
public void sendOneway(Message msg,
    MessageQueue mq) throws MQClientException, RemotingException, InterruptedException {
    this.makeSureStateOK();
    Validators.checkMessage(msg, this.defaultMQProducer);

    try {
        this.sendKernelImpl(msg, mq, CommunicationMode.ONEWAY, null, null, this.defaultMQProducer.getSendMsgTimeout());
    } catch (MQBrokerException e) {
        throw new MQClientException("unknown exception", e);
    }
}
 
Example #14
Source File: ResetOffsetByTimeOldCommand.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static void resetOffset(DefaultMQAdminExt defaultMQAdminExt, String consumerGroup, String topic, long timestamp, boolean force,
    String timeStampStr) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    List<RollbackStats> rollbackStatsList = defaultMQAdminExt.resetOffsetByTimestampOld(consumerGroup, topic, timestamp, force);
    System.out.printf(
        "rollback consumer offset by specified consumerGroup[%s], topic[%s], force[%s], timestamp(string)[%s], timestamp(long)[%s]%n",
        consumerGroup, topic, force, timeStampStr, timestamp);

    System.out.printf("%-20s  %-20s  %-20s  %-20s  %-20s  %-20s%n",
        "#brokerName",
        "#queueId",
        "#brokerOffset",
        "#consumerOffset",
        "#timestampOffset",
        "#rollbackOffset"
    );

    for (RollbackStats rollbackStats : rollbackStatsList) {
        System.out.printf("%-20s  %-20d  %-20d  %-20d  %-20d  %-20d%n",
            UtilAll.frontStringAtLeast(rollbackStats.getBrokerName(), 32),
            rollbackStats.getQueueId(),
            rollbackStats.getBrokerOffset(),
            rollbackStats.getConsumerOffset(),
            rollbackStats.getTimestampOffset(),
            rollbackStats.getRollbackOffset()
        );
    }
}
 
Example #15
Source File: DefaultMQAdminExtImpl.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Map<MessageQueue, Long>> getConsumeStatus(String topic, String group,
    String clientAddr) throws RemotingException,
    MQBrokerException, InterruptedException, MQClientException {
    TopicRouteData topicRouteData = this.examineTopicRouteInfo(topic);
    List<BrokerData> brokerDatas = topicRouteData.getBrokerDatas();
    if (brokerDatas != null && brokerDatas.size() > 0) {
        String addr = brokerDatas.get(0).selectBrokerAddr();
        if (addr != null) {
            return this.mqClientInstance.getMQClientAPIImpl().invokeBrokerToGetConsumerStatus(addr, topic, group, clientAddr,
                timeoutMillis);
        }
    }
    return Collections.EMPTY_MAP;
}
 
Example #16
Source File: ClusterTestRequestProcessorTest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws NoSuchFieldException, IllegalAccessException, RemotingException, MQClientException, InterruptedException {
    NamesrvController namesrvController = new NamesrvController(
        new NamesrvConfig(),
        new NettyServerConfig()
    );

    clusterTestProcessor = new ClusterTestRequestProcessor(namesrvController, "default-producer");
    mQClientAPIImpl = mock(MQClientAPIImpl.class);
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt();
    defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
    ctx = mock(ChannelHandlerContext.class);

    Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
    field.setAccessible(true);
    field.set(defaultMQAdminExtImpl, mqClientInstance);
    field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    field.setAccessible(true);
    field.set(mqClientInstance, mQClientAPIImpl);
    field = ClusterTestRequestProcessor.class.getDeclaredField("adminExt");
    field.setAccessible(true);
    field.set(clusterTestProcessor, defaultMQAdminExt);

    TopicRouteData topicRouteData = new TopicRouteData();
    List<BrokerData> brokerDatas = new ArrayList<>();
    HashMap<Long, String> brokerAddrs = new HashMap<>();
    brokerAddrs.put(1234l, "127.0.0.1:10911");
    BrokerData brokerData = new BrokerData();
    brokerData.setCluster("default-cluster");
    brokerData.setBrokerName("default-broker");
    brokerData.setBrokerAddrs(brokerAddrs);
    brokerDatas.add(brokerData);
    topicRouteData.setBrokerDatas(brokerDatas);
    when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(topicRouteData);
}
 
Example #17
Source File: ValidatorsTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckTopic_HasIllegalCharacters() {
    String illegalTopic = "TOPIC&*^";
    try {
        Validators.checkTopic(illegalTopic);
        failBecauseExceptionWasNotThrown(MQClientException.class);
    } catch (MQClientException e) {
        assertThat(e).hasMessageStartingWith(String.format("The specified topic[%s] contains illegal characters, allowing only %s", illegalTopic, Validators.VALID_PATTERN_STR));
    }
}
 
Example #18
Source File: DefaultMQAdminExtImpl.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public boolean cleanUnusedTopicByCluster(ClusterInfo clusterInfo, String cluster) throws RemotingConnectException,
    RemotingSendRequestException, RemotingTimeoutException, MQClientException, InterruptedException {
    boolean result = false;
    String[] addrs = clusterInfo.retrieveAllAddrByCluster(cluster);
    for (String addr : addrs) {
        result = cleanUnusedTopicByAddr(addr);
    }
    return result;
}
 
Example #19
Source File: DefaultMQPushConsumerImpl.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
public void subscribe(String topic, String subExpression) throws MQClientException {
        try {
//            构建topic订阅数据,默认集群消费=》
            SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData(this.defaultMQPushConsumer.getConsumerGroup(),
                topic, subExpression);
//            存储topic订阅数据=》
            this.rebalanceImpl.getSubscriptionInner().put(topic, subscriptionData);
            if (this.mQClientFactory != null) {
//                同步向所有的broker发送心跳监测=》
                this.mQClientFactory.sendHeartbeatToAllBrokerWithLock();
            }
        } catch (Exception e) {
            throw new MQClientException("subscription exception", e);
        }
    }
 
Example #20
Source File: DefaultMQAdminExtImpl.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Override
public boolean cleanExpiredConsumerQueueByAddr(
    String addr) throws RemotingConnectException, RemotingSendRequestException,
    RemotingTimeoutException, MQClientException, InterruptedException {
    boolean result = mqClientInstance.getMQClientAPIImpl().cleanExpiredConsumeQueue(addr, timeoutMillis);
    log.warn("clean expired ConsumeQueue on target " + addr + " broker " + result);
    return result;
}
 
Example #21
Source File: MQClientAPIImpl.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
public Map<Integer, Long> queryCorrectionOffset(final String addr, final String topic, final String group,
    Set<String> filterGroup,
    long timeoutMillis) throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
    InterruptedException {
    QueryCorrectionOffsetHeader requestHeader = new QueryCorrectionOffsetHeader();
    requestHeader.setCompareGroup(group);
    requestHeader.setTopic(topic);
    if (filterGroup != null) {
        StringBuilder sb = new StringBuilder();
        String splitor = "";
        for (String s : filterGroup) {
            sb.append(splitor).append(s);
            splitor = ",";
        }
        requestHeader.setFilterGroups(sb.toString());
    }
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CORRECTION_OFFSET, requestHeader);

    RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
        request, timeoutMillis);
    assert response != null;
    switch (response.getCode()) {
        case ResponseCode.SUCCESS: {
            if (response.getBody() != null) {
                QueryCorrectionOffsetBody body = QueryCorrectionOffsetBody.decode(response.getBody(), QueryCorrectionOffsetBody.class);
                return body.getCorrectionOffsets();
            }
        }
        default:
            break;
    }

    throw new MQClientException(response.getCode(), response.getRemark());
}
 
Example #22
Source File: ResetOffsetByTimeOldCommand.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void resetOffset(DefaultMQAdminExt defaultMQAdminExt, String consumerGroup, String topic,
    long timestamp, boolean force,
    String timeStampStr) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    List<RollbackStats> rollbackStatsList = defaultMQAdminExt.resetOffsetByTimestampOld(consumerGroup, topic, timestamp, force);
    System.out.printf(
        "rollback consumer offset by specified consumerGroup[%s], topic[%s], force[%s], timestamp(string)[%s], timestamp(long)[%s]%n",
        consumerGroup, topic, force, timeStampStr, timestamp);

    System.out.printf("%-20s  %-20s  %-20s  %-20s  %-20s  %-20s%n",
        "#brokerName",
        "#queueId",
        "#brokerOffset",
        "#consumerOffset",
        "#timestampOffset",
        "#rollbackOffset"
    );

    for (RollbackStats rollbackStats : rollbackStatsList) {
        System.out.printf("%-20s  %-20d  %-20d  %-20d  %-20d  %-20d%n",
            UtilAll.frontStringAtLeast(rollbackStats.getBrokerName(), 32),
            rollbackStats.getQueueId(),
            rollbackStats.getBrokerOffset(),
            rollbackStats.getConsumerOffset(),
            rollbackStats.getTimestampOffset(),
            rollbackStats.getRollbackOffset()
        );
    }
}
 
Example #23
Source File: DefaultMQProducerTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendMessage_ZeroMessage() throws InterruptedException, RemotingException, MQBrokerException {
    try {
        producer.send(zeroMsg);
        failBecauseExceptionWasNotThrown(MQClientException.class);
    } catch (MQClientException e) {
        assertThat(e).hasMessageContaining("message body length is zero");
    }
}
 
Example #24
Source File: DefaultMQPullConsumerImpl.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public void pull(MessageQueue mq, MessageSelector messageSelector, long offset, int maxNums,
    PullCallback pullCallback,
    long timeout)
    throws MQClientException, RemotingException, InterruptedException {
    SubscriptionData subscriptionData = getSubscriptionData(mq, messageSelector);
    this.pullAsyncImpl(mq, subscriptionData, offset, maxNums, pullCallback, false, timeout);
}
 
Example #25
Source File: Consumer.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException {
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_3");

    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

    consumer.subscribe("TopicTest", "TagA || TagC || TagD");

    consumer.registerMessageListener(new MessageListenerOrderly() {
        AtomicLong consumeTimes = new AtomicLong(0);

        @Override
        public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
            context.setAutoCommit(false);
            System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
            this.consumeTimes.incrementAndGet();
            if ((this.consumeTimes.get() % 2) == 0) {
                return ConsumeOrderlyStatus.SUCCESS;
            } else if ((this.consumeTimes.get() % 3) == 0) {
                return ConsumeOrderlyStatus.ROLLBACK;
            } else if ((this.consumeTimes.get() % 4) == 0) {
                return ConsumeOrderlyStatus.COMMIT;
            } else if ((this.consumeTimes.get() % 5) == 0) {
                context.setSuspendCurrentQueueTimeMillis(3000);
                return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
            }

            return ConsumeOrderlyStatus.SUCCESS;
        }
    });

    consumer.start();
    System.out.printf("Consumer Started.%n");
}
 
Example #26
Source File: DefaultMQAdminExtImpl.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
@Override
public List<QueueTimeSpan> queryConsumeTimeSpan(final String topic,
    final String group) throws InterruptedException, MQBrokerException,
    RemotingException, MQClientException {
    List<QueueTimeSpan> spanSet = new ArrayList<QueueTimeSpan>();
    TopicRouteData topicRouteData = this.examineTopicRouteInfo(topic);
    for (BrokerData bd : topicRouteData.getBrokerDatas()) {
        String addr = bd.selectBrokerAddr();
        if (addr != null) {
            spanSet.addAll(this.mqClientInstance.getMQClientAPIImpl().queryConsumeTimeSpan(addr, topic, group, timeoutMillis));
        }
    }
    return spanSet;
}
 
Example #27
Source File: MQClientAPIImpl.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public TopicList getHasUnitSubTopicList(final boolean containRetry, final long timeoutMillis)
    throws RemotingException, MQClientException, InterruptedException {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_HAS_UNIT_SUB_TOPIC_LIST, null);

    RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
    assert response != null;
    switch (response.getCode()) {
        case ResponseCode.SUCCESS: {
            byte[] body = response.getBody();
            if (body != null) {
                TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
                if (!containRetry) {
                    Iterator<String> it = topicList.getTopicList().iterator();
                    while (it.hasNext()) {
                        String topic = it.next();
                        if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX))
                            it.remove();
                    }
                }
                return topicList;
            }
        }
        default:
            break;
    }

    throw new MQClientException(response.getCode(), response.getRemark());
}
 
Example #28
Source File: LocalMessageCache.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
void ack(final String messageId) {
    ConsumeRequest consumeRequest = consumedRequest.remove(messageId);
    if (consumeRequest != null) {
        long offset = consumeRequest.getProcessQueue().removeMessage(Collections.singletonList(consumeRequest.getMessageExt()));
        try {
            rocketmqPullConsumer.updateConsumeOffset(consumeRequest.getMessageQueue(), offset);
        } catch (MQClientException e) {
            log.error("A error occurred in update consume offset process.", e);
        }
    }
}
 
Example #29
Source File: DefaultMQPullConsumerImpl.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void copySubscription() throws MQClientException {
    try {
        Set<String> registerTopics = this.defaultMQPullConsumer.getRegisterTopics();
        if (registerTopics != null) {
            for (final String topic : registerTopics) {
                SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData(this.defaultMQPullConsumer.getConsumerGroup(),
                    topic, SubscriptionData.SUB_ALL);
                this.rebalanceImpl.getSubscriptionInner().put(topic, subscriptionData);
            }
        }
    } catch (Exception e) {
        throw new MQClientException("subscription exception", e);
    }
}
 
Example #30
Source File: RMQNormalConsumer.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
public void create() {
    consumer = new DefaultMQPushConsumer(consumerGroup);
    consumer.setInstanceName(RandomUtil.getStringByUUID());
    consumer.setNamesrvAddr(nsAddr);
    try {
        consumer.subscribe(topic, subExpression);
    } catch (MQClientException e) {
        logger.error("consumer subscribe failed!");
        e.printStackTrace();
    }
    consumer.setMessageListener(listner);
}