Search in sources :

Example 1 with SendResult

use of org.apache.rocketmq.client.producer.SendResult in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MessageExceptionIT method testSendMsgWithUserProperty.

@Test
public void testSendMsgWithUserProperty() {
    Message msg = MessageFactory.getRandomMessage(topic);
    msg.putUserProperty("key", RandomUtils.getCheseWord(10 * 1024));
    SendResult sendResult = null;
    try {
        sendResult = producer.send(msg);
    } catch (Exception e) {
    }
    assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
}
Also used : Message(org.apache.rocketmq.common.message.Message) SendResult(org.apache.rocketmq.client.producer.SendResult) Test(org.junit.Test)

Example 2 with SendResult

use of org.apache.rocketmq.client.producer.SendResult in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class QueryMsgByIdSubCommand method sendMsg.

private void sendMsg(final DefaultMQAdminExt defaultMQAdminExt, final DefaultMQProducer defaultMQProducer, final String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    try {
        MessageExt msg = defaultMQAdminExt.viewMessage(msgId);
        if (msg != null) {
            // resend msg by id
            System.out.printf("prepare resend msg. originalMsgId=" + msgId);
            SendResult result = defaultMQProducer.send(msg);
            System.out.printf("%s", result);
        } else {
            System.out.printf("no message. msgId=" + msgId);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : MessageExt(org.apache.rocketmq.common.message.MessageExt) SendResult(org.apache.rocketmq.client.producer.SendResult) IOException(java.io.IOException) 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)

Example 3 with SendResult

use of org.apache.rocketmq.client.producer.SendResult in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class DefaultMQProducerImpl method sendDefaultImpl.

// 发送消息核心
private // 
SendResult sendDefaultImpl(// 
Message msg, // 
final CommunicationMode communicationMode, // 
final SendCallback sendCallback, // 
final long timeout) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    // 判断服务是否可用
    this.makeSureStateOK();
    // 消息验证
    Validators.checkMessage(msg, this.defaultMQProducer);
    final long invokeID = random.nextLong();
    long beginTimestampFirst = System.currentTimeMillis();
    long beginTimestampPrev = beginTimestampFirst;
    long endTimestamp = beginTimestampFirst;
    // 获取topic路由信息
    TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
    if (topicPublishInfo != null && topicPublishInfo.ok()) {
        MessageQueue mq = null;
        Exception exception = null;
        SendResult sendResult = null;
        // 发送模式是sync 会有3次其他1次
        int timesTotal = communicationMode == CommunicationMode.SYNC ? 1 + this.defaultMQProducer.getRetryTimesWhenSendFailed() : 1;
        int times = 0;
        String[] brokersSent = new String[timesTotal];
        for (; times < timesTotal; times++) {
            // 第一次的确是null 但是如果第二次呢? 所以这里存在的意义
            String lastBrokerName = null == mq ? null : mq.getBrokerName();
            // 选择一个queue
            MessageQueue tmpmq = this.selectOneMessageQueue(topicPublishInfo, lastBrokerName);
            if (tmpmq != null) {
                mq = tmpmq;
                brokersSent[times] = mq.getBrokerName();
                try {
                    beginTimestampPrev = System.currentTimeMillis();
                    // 调用sendKernelImpl发送消息  发送消息核心
                    sendResult = this.sendKernelImpl(msg, mq, communicationMode, sendCallback, topicPublishInfo, timeout);
                    endTimestamp = System.currentTimeMillis();
                    // 更新Broker可用信息
                    this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, false);
                    switch(communicationMode) {
                        case ASYNC:
                            return null;
                        case ONEWAY:
                            return null;
                        case SYNC:
                            if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
                                if (this.defaultMQProducer.isRetryAnotherBrokerWhenNotStoreOK()) {
                                    continue;
                                }
                            }
                            return sendResult;
                        default:
                            break;
                    }
                } catch (RemotingException e) {
                    endTimestamp = System.currentTimeMillis();
                    this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, true);
                    log.warn(String.format("sendKernelImpl exception, resend at once, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
                    log.warn(msg.toString());
                    exception = e;
                    continue;
                } catch (MQClientException e) {
                    endTimestamp = System.currentTimeMillis();
                    this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, true);
                    log.warn(String.format("sendKernelImpl exception, resend at once, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
                    log.warn(msg.toString());
                    exception = e;
                    continue;
                } catch (MQBrokerException e) {
                    endTimestamp = System.currentTimeMillis();
                    this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, true);
                    log.warn(String.format("sendKernelImpl exception, resend at once, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
                    log.warn(msg.toString());
                    exception = e;
                    switch(e.getResponseCode()) {
                        // 如下异常continue,进行发送消息重试
                        case ResponseCode.TOPIC_NOT_EXIST:
                        case ResponseCode.SERVICE_NOT_AVAILABLE:
                        case ResponseCode.SYSTEM_ERROR:
                        case ResponseCode.NO_PERMISSION:
                        case ResponseCode.NO_BUYER_ID:
                        case ResponseCode.NOT_IN_CURRENT_UNIT:
                            continue;
                        default:
                            if (sendResult != null) {
                                return sendResult;
                            }
                            throw e;
                    }
                } catch (InterruptedException e) {
                    endTimestamp = System.currentTimeMillis();
                    this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, false);
                    log.warn(String.format("sendKernelImpl exception, throw exception, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
                    log.warn(msg.toString());
                    log.warn("sendKernelImpl exception", e);
                    log.warn(msg.toString());
                    throw e;
                }
            } else {
                break;
            }
        }
        if (sendResult != null) {
            return sendResult;
        }
        String info = String.format("Send [%d] times, still failed, cost [%d]ms, Topic: %s, BrokersSent: %s", times, System.currentTimeMillis() - beginTimestampFirst, msg.getTopic(), Arrays.toString(brokersSent));
        info += FAQUrl.suggestTodo(FAQUrl.SEND_MSG_FAILED);
        MQClientException mqClientException = new MQClientException(info, exception);
        if (exception instanceof MQBrokerException) {
            mqClientException.setResponseCode(((MQBrokerException) exception).getResponseCode());
        } else if (exception instanceof RemotingConnectException) {
            mqClientException.setResponseCode(ClientErrorCode.CONNECT_BROKER_EXCEPTION);
        } else if (exception instanceof RemotingTimeoutException) {
            mqClientException.setResponseCode(ClientErrorCode.ACCESS_BROKER_TIMEOUT);
        } else if (exception instanceof MQClientException) {
            mqClientException.setResponseCode(ClientErrorCode.BROKER_NOT_EXIST_EXCEPTION);
        }
        throw mqClientException;
    }
    List<String> nsList = this.getmQClientFactory().getMQClientAPIImpl().getNameServerAddressList();
    if (null == nsList || nsList.isEmpty()) {
        throw new MQClientException("No name server address, please set it." + FAQUrl.suggestTodo(FAQUrl.NAME_SERVER_ADDR_NOT_EXIST_URL), null).setResponseCode(ClientErrorCode.NO_NAME_SERVER_EXCEPTION);
    }
    throw new MQClientException("No route info of this topic, " + msg.getTopic() + FAQUrl.suggestTodo(FAQUrl.NO_TOPIC_ROUTE_INFO), null).setResponseCode(ClientErrorCode.NOT_FOUND_TOPIC_EXCEPTION);
}
Also used : RemotingConnectException(org.apache.rocketmq.remoting.exception.RemotingConnectException) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException) MQClientException(org.apache.rocketmq.client.exception.MQClientException) RemotingConnectException(org.apache.rocketmq.remoting.exception.RemotingConnectException) RemotingTimeoutException(org.apache.rocketmq.remoting.exception.RemotingTimeoutException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) RemotingTimeoutException(org.apache.rocketmq.remoting.exception.RemotingTimeoutException) TransactionSendResult(org.apache.rocketmq.client.producer.TransactionSendResult) SendResult(org.apache.rocketmq.client.producer.SendResult) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) MQClientException(org.apache.rocketmq.client.exception.MQClientException)

Example 4 with SendResult

use of org.apache.rocketmq.client.producer.SendResult in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MQClientAPIImplTest method testSendMessageSync_Success.

@Test
public void testSendMessageSync_Success() throws InterruptedException, RemotingException, MQBrokerException {
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock mock) throws Throwable {
            RemotingCommand request = mock.getArgument(1);
            return createSuccessResponse(request);
        }
    }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());
    SendMessageRequestHeader requestHeader = createSendMessageRequestHeader();
    SendResult sendResult = mqClientAPI.sendMessage(brokerAddr, brokerName, msg, requestHeader, 3 * 1000, CommunicationMode.SYNC, new SendMessageContext(), defaultMQProducerImpl);
    assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
    assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
    assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
    assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
}
Also used : RemotingCommand(org.apache.rocketmq.remoting.protocol.RemotingCommand) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) SendMessageRequestHeader(org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader) InvocationOnMock(org.mockito.invocation.InvocationOnMock) SendResult(org.apache.rocketmq.client.producer.SendResult) SendMessageContext(org.apache.rocketmq.client.hook.SendMessageContext) Test(org.junit.Test)

Example 5 with SendResult

use of org.apache.rocketmq.client.producer.SendResult in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class MQClientAPIImplTest method testSendMessageAsync_Success.

@Test
public void testSendMessageAsync_Success() throws RemotingException, InterruptedException, MQBrokerException {
    doNothing().when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
    SendResult sendResult = mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(), 3 * 1000, CommunicationMode.ASYNC, new SendMessageContext(), defaultMQProducerImpl);
    assertThat(sendResult).isNull();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock mock) throws Throwable {
            InvokeCallback callback = mock.getArgument(3);
            RemotingCommand request = mock.getArgument(1);
            ResponseFuture responseFuture = new ResponseFuture(request.getOpaque(), 3 * 1000, null, null);
            responseFuture.setResponseCommand(createSuccessResponse(request));
            callback.operationComplete(responseFuture);
            return null;
        }
    }).when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
    SendMessageContext sendMessageContext = new SendMessageContext();
    sendMessageContext.setProducer(new DefaultMQProducerImpl(new DefaultMQProducer()));
    mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(), 3 * 1000, CommunicationMode.ASYNC, new SendCallback() {

        @Override
        public void onSuccess(SendResult sendResult) {
            assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
            assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
            assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
            assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
        }

        @Override
        public void onException(Throwable e) {
        }
    }, null, null, 0, sendMessageContext, defaultMQProducerImpl);
}
Also used : InvokeCallback(org.apache.rocketmq.remoting.InvokeCallback) SendMessageRequestHeader(org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader) ResponseFuture(org.apache.rocketmq.remoting.netty.ResponseFuture) DefaultMQProducer(org.apache.rocketmq.client.producer.DefaultMQProducer) RemotingCommand(org.apache.rocketmq.remoting.protocol.RemotingCommand) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) SendResult(org.apache.rocketmq.client.producer.SendResult) SendMessageContext(org.apache.rocketmq.client.hook.SendMessageContext) DefaultMQProducerImpl(org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl) SendCallback(org.apache.rocketmq.client.producer.SendCallback) Test(org.junit.Test)

Aggregations

SendResult (org.apache.rocketmq.client.producer.SendResult)95 Message (org.apache.rocketmq.common.message.Message)64 DefaultMQProducer (org.apache.rocketmq.client.producer.DefaultMQProducer)42 MQClientException (org.apache.rocketmq.client.exception.MQClientException)39 Test (org.junit.Test)32 MQBrokerException (org.apache.rocketmq.client.exception.MQBrokerException)15 RemotingException (org.apache.rocketmq.remoting.exception.RemotingException)15 SendCallback (org.apache.rocketmq.client.producer.SendCallback)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11 MessageQueue (org.apache.rocketmq.common.message.MessageQueue)10 ArrayList (java.util.ArrayList)8 SendMessageContext (org.apache.rocketmq.client.hook.SendMessageContext)8 SendMessageRequestHeader (org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader)8 RemotingCommand (org.apache.rocketmq.remoting.protocol.RemotingCommand)8 IOException (java.io.IOException)6 TransactionSendResult (org.apache.rocketmq.client.producer.TransactionSendResult)6 RemotingConnectException (org.apache.rocketmq.remoting.exception.RemotingConnectException)6 RemotingTimeoutException (org.apache.rocketmq.remoting.exception.RemotingTimeoutException)6 MessageExt (org.apache.rocketmq.common.message.MessageExt)5 BytesMessage (io.openmessaging.BytesMessage)4