Search in sources :

Example 61 with SendResult

use of org.apache.rocketmq.client.producer.SendResult in project paascloud-master by paascloud.

the class RocketMqProducer method retrySendMessage.

private static SendResult retrySendMessage(String pid, Message msg) {
    int iniCount = 1;
    SendResult result;
    while (true) {
        try {
            result = MqProducerBeanFactory.getBean(pid).send(msg);
            break;
        } catch (Exception e) {
            log.error("发送消息失败:", e);
            if (iniCount++ >= PRODUCER_RETRY_TIMES) {
                throw new TpcBizException(ErrorCodeEnum.TPC100500014, msg.getTopic(), msg.getKeys());
            }
        }
    }
    log.info("<== 发送MQ SendResult={}", result);
    return result;
}
Also used : SendResult(org.apache.rocketmq.client.producer.SendResult) TpcBizException(com.paascloud.provider.exceptions.TpcBizException) TpcBizException(com.paascloud.provider.exceptions.TpcBizException)

Example 62 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 sendKernelImpl.

private // 
SendResult sendKernelImpl(// 
final Message msg, // 
final MessageQueue mq, // 
final CommunicationMode communicationMode, // 
final SendCallback sendCallback, // 
final TopicPublishInfo topicPublishInfo, final long timeout) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    // 获取 broker地址
    String brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());
    if (null == brokerAddr) {
        tryToFindTopicPublishInfo(mq.getTopic());
        brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());
    }
    SendMessageContext context = null;
    if (brokerAddr != null) {
        brokerAddr = MixAll.brokerVIPChannel(this.defaultMQProducer.isSendMessageWithVIPChannel(), brokerAddr);
        byte[] prevBody = msg.getBody();
        try {
            // for MessageBatch,ID has been set in the generating process
            if (!(msg instanceof MessageBatch)) {
                // 设置设置UNIQ_id,所以当看见msgId的时候为什么解析不一样了懂了吧
                MessageClientIDSetter.setUniqID(msg);
            }
            // 又是根据位来进行每位是啥的判断
            int sysFlag = 0;
            if (this.tryToCompressMessage(msg)) {
                sysFlag |= MessageSysFlag.COMPRESSED_FLAG;
            }
            // 根据事务属性key获取值看是否是事务消息
            final String tranMsg = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);
            if (tranMsg != null && Boolean.parseBoolean(tranMsg)) {
                sysFlag |= MessageSysFlag.TRANSACTION_PREPARED_TYPE;
            }
            if (hasCheckForbiddenHook()) {
                CheckForbiddenContext checkForbiddenContext = new CheckForbiddenContext();
                checkForbiddenContext.setNameSrvAddr(this.defaultMQProducer.getNamesrvAddr());
                checkForbiddenContext.setGroup(this.defaultMQProducer.getProducerGroup());
                checkForbiddenContext.setCommunicationMode(communicationMode);
                checkForbiddenContext.setBrokerAddr(brokerAddr);
                checkForbiddenContext.setMessage(msg);
                checkForbiddenContext.setMq(mq);
                checkForbiddenContext.setUnitMode(this.isUnitMode());
                this.executeCheckForbiddenHook(checkForbiddenContext);
            }
            if (this.hasSendMessageHook()) {
                context = new SendMessageContext();
                context.setProducer(this);
                context.setProducerGroup(this.defaultMQProducer.getProducerGroup());
                context.setCommunicationMode(communicationMode);
                context.setBornHost(this.defaultMQProducer.getClientIP());
                context.setBrokerAddr(brokerAddr);
                context.setMessage(msg);
                context.setMq(mq);
                String isTrans = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);
                if (isTrans != null && isTrans.equals("true")) {
                    context.setMsgType(MessageType.Trans_Msg_Half);
                }
                if (msg.getProperty("__STARTDELIVERTIME") != null || msg.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL) != null) {
                    context.setMsgType(MessageType.Delay_Msg);
                }
                this.executeSendMessageHookBefore(context);
            }
            // 构建SendMessageRequestHeader
            SendMessageRequestHeader requestHeader = new SendMessageRequestHeader();
            requestHeader.setProducerGroup(this.defaultMQProducer.getProducerGroup());
            requestHeader.setTopic(msg.getTopic());
            requestHeader.setDefaultTopic(this.defaultMQProducer.getCreateTopicKey());
            requestHeader.setDefaultTopicQueueNums(this.defaultMQProducer.getDefaultTopicQueueNums());
            requestHeader.setQueueId(mq.getQueueId());
            requestHeader.setSysFlag(sysFlag);
            // 生成消息时间戳
            requestHeader.setBornTimestamp(System.currentTimeMillis());
            requestHeader.setFlag(msg.getFlag());
            requestHeader.setProperties(MessageDecoder.messageProperties2String(msg.getProperties()));
            requestHeader.setReconsumeTimes(0);
            requestHeader.setUnitMode(this.isUnitMode());
            requestHeader.setBatch(msg instanceof MessageBatch);
            if (requestHeader.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
                String reconsumeTimes = MessageAccessor.getReconsumeTime(msg);
                if (reconsumeTimes != null) {
                    requestHeader.setReconsumeTimes(Integer.valueOf(reconsumeTimes));
                    MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_RECONSUME_TIME);
                }
                String maxReconsumeTimes = MessageAccessor.getMaxReconsumeTimes(msg);
                if (maxReconsumeTimes != null) {
                    requestHeader.setMaxReconsumeTimes(Integer.valueOf(maxReconsumeTimes));
                    MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_MAX_RECONSUME_TIMES);
                }
            }
            SendResult sendResult = null;
            switch(communicationMode) {
                case ASYNC:
                    sendResult = // 异步发送消息
                    this.mQClientFactory.getMQClientAPIImpl().sendMessage(// 1
                    brokerAddr, // 2
                    mq.getBrokerName(), // 3
                    msg, // 4
                    requestHeader, // 5
                    timeout, // 6
                    communicationMode, // 7
                    sendCallback, // 8
                    topicPublishInfo, // 9
                    this.mQClientFactory, // 10
                    this.defaultMQProducer.getRetryTimesWhenSendAsyncFailed(), // 
                    context, this);
                    break;
                case ONEWAY:
                case SYNC:
                    sendResult = // 同步以及广播发送消息
                    this.mQClientFactory.getMQClientAPIImpl().sendMessage(brokerAddr, mq.getBrokerName(), msg, requestHeader, timeout, communicationMode, context, this);
                    break;
                default:
                    assert false;
                    break;
            }
            if (this.hasSendMessageHook()) {
                context.setSendResult(sendResult);
                // 发送消息后逻辑
                this.executeSendMessageHookAfter(context);
            }
            return sendResult;
        } catch (RemotingException e) {
            if (this.hasSendMessageHook()) {
                context.setException(e);
                this.executeSendMessageHookAfter(context);
            }
            throw e;
        } catch (MQBrokerException e) {
            if (this.hasSendMessageHook()) {
                context.setException(e);
                this.executeSendMessageHookAfter(context);
            }
            throw e;
        } catch (InterruptedException e) {
            if (this.hasSendMessageHook()) {
                context.setException(e);
                this.executeSendMessageHookAfter(context);
            }
            throw e;
        } finally {
            msg.setBody(prevBody);
        }
    }
    throw new MQClientException("The broker[" + mq.getBrokerName() + "] not exist", null);
}
Also used : MessageBatch(org.apache.rocketmq.common.message.MessageBatch) CheckForbiddenContext(org.apache.rocketmq.client.hook.CheckForbiddenContext) SendMessageRequestHeader(org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader) MQBrokerException(org.apache.rocketmq.client.exception.MQBrokerException) SendMessageContext(org.apache.rocketmq.client.hook.SendMessageContext) 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 63 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 sendMessageInTransaction.

public TransactionSendResult sendMessageInTransaction(final Message msg, final LocalTransactionExecuter tranExecuter, final Object arg) throws MQClientException {
    if (null == tranExecuter) {
        throw new MQClientException("tranExecutor is null", null);
    }
    Validators.checkMessage(msg, this.defaultMQProducer);
    SendResult sendResult = null;
    MessageAccessor.putProperty(msg, MessageConst.PROPERTY_TRANSACTION_PREPARED, "true");
    MessageAccessor.putProperty(msg, MessageConst.PROPERTY_PRODUCER_GROUP, this.defaultMQProducer.getProducerGroup());
    try {
        sendResult = this.send(msg);
    } catch (Exception e) {
        throw new MQClientException("send message Exception", e);
    }
    LocalTransactionState localTransactionState = LocalTransactionState.UNKNOW;
    Throwable localException = null;
    switch(sendResult.getSendStatus()) {
        case SEND_OK:
            {
                try {
                    if (sendResult.getTransactionId() != null) {
                        msg.putUserProperty("__transactionId__", sendResult.getTransactionId());
                    }
                    localTransactionState = tranExecuter.executeLocalTransactionBranch(msg, arg);
                    if (null == localTransactionState) {
                        localTransactionState = LocalTransactionState.UNKNOW;
                    }
                    if (localTransactionState != LocalTransactionState.COMMIT_MESSAGE) {
                        log.info("executeLocalTransactionBranch return {}", localTransactionState);
                        log.info(msg.toString());
                    }
                } catch (Throwable e) {
                    log.info("executeLocalTransactionBranch exception", e);
                    log.info(msg.toString());
                    localException = e;
                }
            }
            break;
        case FLUSH_DISK_TIMEOUT:
        case FLUSH_SLAVE_TIMEOUT:
        case SLAVE_NOT_AVAILABLE:
            localTransactionState = LocalTransactionState.ROLLBACK_MESSAGE;
            break;
        default:
            break;
    }
    try {
        this.endTransaction(sendResult, localTransactionState, localException);
    } catch (Exception e) {
        log.warn("local transaction execute " + localTransactionState + ", but end broker transaction failed", e);
    }
    TransactionSendResult transactionSendResult = new TransactionSendResult();
    transactionSendResult.setSendStatus(sendResult.getSendStatus());
    transactionSendResult.setMessageQueue(sendResult.getMessageQueue());
    transactionSendResult.setMsgId(sendResult.getMsgId());
    transactionSendResult.setQueueOffset(sendResult.getQueueOffset());
    transactionSendResult.setTransactionId(sendResult.getTransactionId());
    transactionSendResult.setLocalTransactionState(localTransactionState);
    return transactionSendResult;
}
Also used : LocalTransactionState(org.apache.rocketmq.client.producer.LocalTransactionState) TransactionSendResult(org.apache.rocketmq.client.producer.TransactionSendResult) SendResult(org.apache.rocketmq.client.producer.SendResult) TransactionSendResult(org.apache.rocketmq.client.producer.TransactionSendResult) MQClientException(org.apache.rocketmq.client.exception.MQClientException) 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)

Example 64 with SendResult

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

the class SequenceProducerImplTest method testSend_WithCommit.

@Test
public void testSend_WithCommit() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
    SendResult sendResult = new SendResult();
    sendResult.setMsgId("TestMsgID");
    sendResult.setSendStatus(SendStatus.SEND_OK);
    when(rocketmqProducer.send(ArgumentMatchers.<Message>anyList())).thenReturn(sendResult);
    when(rocketmqProducer.getMaxMessageSize()).thenReturn(1024);
    final BytesMessage message = producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] { 'a' });
    producer.send(message);
    producer.commit();
    assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo("TestMsgID");
}
Also used : SendResult(org.apache.rocketmq.client.producer.SendResult) BytesMessage(io.openmessaging.BytesMessage) Test(org.junit.Test)

Example 65 with SendResult

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

the class SequenceProducerImpl method commit.

@Override
public synchronized void commit() {
    List<Message> messages = new ArrayList<>();
    msgCacheQueue.drainTo(messages);
    List<org.apache.rocketmq.common.message.Message> rmqMessages = new ArrayList<>();
    for (Message message : messages) {
        rmqMessages.add(OMSUtil.msgConvert((BytesMessage) message));
    }
    if (rmqMessages.size() == 0) {
        return;
    }
    try {
        SendResult sendResult = this.rocketmqProducer.send(rmqMessages);
        String[] msgIdArray = sendResult.getMsgId().split(",");
        for (int i = 0; i < messages.size(); i++) {
            Message message = messages.get(i);
            message.headers().put(MessageHeader.MESSAGE_ID, msgIdArray[i]);
        }
    } catch (Exception e) {
        throw checkProducerException("", "", e);
    }
}
Also used : Message(io.openmessaging.Message) BytesMessage(io.openmessaging.BytesMessage) SendResult(org.apache.rocketmq.client.producer.SendResult) ArrayList(java.util.ArrayList) BytesMessage(io.openmessaging.BytesMessage) MQClientException(org.apache.rocketmq.client.exception.MQClientException)

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