Java Code Examples for org.apache.rocketmq.client.producer.SendStatus#SEND_OK

The following examples show how to use org.apache.rocketmq.client.producer.SendStatus#SEND_OK . 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: CarreraRequest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
/**
 * RMQ send callback
 *
 * @param sendResult
 */
@Override
public void onSuccess(SendResult sendResult) {
    if (isFinished()) return;
    if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
        LOGGER.warn("RMQSendResult.Status={},request={},elapse:{}", sendResult.getSendStatus(), this, TimeUtils.getElapseTime(startTime));
    }
    onFinish(ProxySendResult.OK);
}
 
Example 2
Source File: CarreraRequest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
/**
 * RMQ send callback
 *
 * @param sendResult
 */
@Override
public void onSuccess(SendResult sendResult) {
    if (isFinished()) return;
    if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
        LOGGER.warn("RMQSendResult.Status={},request={},elapse:{}", sendResult.getSendStatus(), this, TimeUtils.getElapseTime(startTime));
    }
    onFinish(ProxySendResult.OK);
}
 
Example 3
Source File: AbstractMQTransactionProducer.java    From rocketmq-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
public SendResult sendMessageInTransaction(Message msg, Object arg) throws MQException {
    try {
        SendResult sendResult = transactionProducer.sendMessageInTransaction(msg, arg);
        if(sendResult.getSendStatus() != SendStatus.SEND_OK) {
            log.error("事务消息发送失败,topic : {}, msgObj {}", msg.getTopic(), msg);
            throw new MQException("事务消息发送失败,topic :" + msg.getTopic() + ", status :" + sendResult.getSendStatus());
        }
        log.info("发送事务消息成功,事务id: {}", msg.getTransactionId());
        return sendResult;
    } catch (Exception e) {
        log.error("事务消息发送失败,topic : {}, msgObj {}", msg.getTopic(), msg);
        throw new MQException("事务消息发送失败,topic :" + msg.getTopic() + ",e:" + e.getMessage());
    }
}
 
Example 4
Source File: DefaultRocketMqProducer.java    From spring-boot-rocketmq-starter with Apache License 2.0 5 votes vote down vote up
/**
 * send msg.
 *
 * @param msg content
 * @return send result
 */
public boolean sendMsg(Message msg) {
    SendResult sendResult = null;
    try {
        sendResult = producer.send(msg);
    } catch (Exception e) {
        logger.error("send msg error", e);
    }
    return sendResult != null && sendResult.getSendStatus() == SendStatus.SEND_OK;
}
 
Example 5
Source File: DefaultRocketMqProducer.java    From spring-boot-rocketmq-starter with Apache License 2.0 5 votes vote down vote up
/**
 * send delay msg.
 *
 * @param msg content
 * @param delayLevel 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
 * @return send result
 */
public boolean sendDelayMsg(String topic, String tag, Message msg, int delayLevel) {
    msg.setDelayTimeLevel(delayLevel);
    SendResult sendResult = null;
    try {
        sendResult = producer.send(msg);
    } catch (Exception e) {
        logger.error("send msg error", e);
    }
    return sendResult != null && sendResult.getSendStatus() == SendStatus.SEND_OK;
}
 
Example 6
Source File: OnSuccessInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    SendCallBackEnhanceInfo enhanceInfo = (SendCallBackEnhanceInfo) objInst.getSkyWalkingDynamicField();
    AbstractSpan activeSpan = ContextManager.createLocalSpan(CALLBACK_OPERATION_NAME_PREFIX + enhanceInfo.getTopicId() + "/Producer/Callback");
    activeSpan.setComponent(ComponentsDefine.ROCKET_MQ_PRODUCER);
    SendStatus sendStatus = ((SendResult) allArguments[0]).getSendStatus();
    if (sendStatus != SendStatus.SEND_OK) {
        activeSpan.errorOccurred();
        Tags.STATUS_CODE.set(activeSpan, sendStatus.name());
    }
    ContextManager.continued(enhanceInfo.getContextSnapshot());
}
 
Example 7
Source File: SecKillChargeServiceImpl.java    From seckill-rocketmq with Apache License 2.0 4 votes vote down vote up
/**
 * 秒杀订单入队
 * @param chargeOrderRequest
 * @param sessionId
 * @return
 */
@Override
public Result secKillOrderEnqueue(ChargeOrderRequest chargeOrderRequest, String sessionId) {

    // 订单号生成,组装秒杀订单消息协议
    String orderId = UUID.randomUUID().toString();
    String phoneNo = chargeOrderRequest.getUserPhoneNum();

    ChargeOrderMsgProtocol msgProtocol = new ChargeOrderMsgProtocol();
    msgProtocol.setUserPhoneNo(phoneNo)
            .setProdId(chargeOrderRequest.getProdId())
            .setChargeMoney(chargeOrderRequest.getChargePrice())
            .setOrderId(orderId);
    String msgBody = msgProtocol.encode();
    LOGGER.info("秒杀订单入队,消息协议={}", msgBody);

    DefaultMQProducer mqProducer = secKillChargeOrderProducer.getProducer();
    // 组装RocketMQ消息体
    Message message = new Message(MessageProtocolConst.SECKILL_CHARGE_ORDER_TOPIC.getTopic(), msgBody.getBytes());
    try {
        // 消息发送
        SendResult sendResult = mqProducer.send(message);
        // TODO 判断SendStatus
        if (sendResult == null) {
            LOGGER.error("sessionId={},秒杀订单消息投递失败,下单失败.msgBody={},sendResult=null", sessionId, msgBody);
            return Result.error(CodeMsg.BIZ_ERROR);
        }
        if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
            LOGGER.error("sessionId={},秒杀订单消息投递失败,下单失败.msgBody={},sendResult=null", sessionId, msgBody);
            return Result.error(CodeMsg.BIZ_ERROR);
        }
        ChargeOrderResponse chargeOrderResponse = new ChargeOrderResponse();
        BeanUtils.copyProperties(msgProtocol, chargeOrderResponse);
        LOGGER.info("sessionId={},秒杀订单消息投递成功,订单入队.出参chargeOrderResponse={},sendResult={}", sessionId, chargeOrderResponse.toString(), JSON.toJSONString(sendResult));
        return Result.success(CodeMsg.ORDER_INLINE, chargeOrderResponse);
    } catch (Exception e) {
        int sendRetryTimes = mqProducer.getRetryTimesWhenSendFailed();
        LOGGER.error("sessionId={},sendRetryTimes={},秒杀订单消息投递异常,下单失败.msgBody={},e={}", sessionId, sendRetryTimes, msgBody, LogExceptionWapper.getStackTrace(e));
    }
    return Result.error(CodeMsg.BIZ_ERROR);
}
 
Example 8
Source File: Utils.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public static void checkSend(String cluster, String nameSvr, String address) throws MQClientException, NoSuchFieldException,
        SecurityException, InterruptedException, IllegalArgumentException, IllegalAccessException, UnsupportedEncodingException, MQBrokerException, RemotingException {

    if (!isBrokerTopicWritable(cluster, nameSvr, address)) {
        return;
    }

    DefaultMQProducer producer = getSendCheckProducer(nameSvr, cluster, address);
    MQClientInstance instance = producer.getDefaultMQProducerImpl().getmQClientFactory();
    Field f = MQClientInstance.class.getDeclaredField("brokerAddrTable");
    f.setAccessible(true);

    Field f2 = MQClientInstance.class.getDeclaredField("scheduledExecutorService");
    f2.setAccessible(true);

    ScheduledExecutorService service = (ScheduledExecutorService) f2.get(instance);
    service.shutdown();
    service.awaitTermination(1000, TimeUnit.SECONDS);

    ConcurrentHashMap<String, HashMap<Long, String>> map = (ConcurrentHashMap<String, HashMap<Long, String>>) f
            .get(instance);
    HashMap<Long, String> addresses = new HashMap<>();
    addresses.put(0L, address);
    map.put("rmqmonitor_" + address, addresses);

    MessageQueue queue = new MessageQueue("SELF_TEST_TOPIC", "rmqmonitor_" + address, 0);
    boolean sendOk = false;
    SendResult sendResult = null;
    for (int i = 0; i < 2; i++) {
        try {
            Message msg = new Message("SELF_TEST_TOPIC", // topic
                    "TagA", // tag
                    ("Hello RocketMQ " + i).getBytes()// body
            );
            sendResult = producer.send(msg, queue);
            if (sendResult.getSendStatus() == SendStatus.SEND_OK || sendResult.getSendStatus() == SLAVE_NOT_AVAILABLE) {
                sendOk = true;
                break;
            }

            logger.warn("send result failed, SendResult={}, cluster={}, namesvr={}, address={}", sendResult, cluster, nameSvr, address);
        } catch (Exception e) {
            logger.error("send exception, cluster={}, namesvr={}, address={}", cluster, nameSvr, address, e);
        }
        Thread.sleep(1000);
    }

    // 报警
    if (!sendOk) {
        logger.error(String.format("[AlarmSendErr] cluster=%s, broker=%s, result=%s", cluster, address, sendResult == null ? "null" : sendResult.toString()));
    } else {
        logger.info("AlarmSendCheck cluster={}, broker={}, result={}", cluster, address, sendResult.toString());
    }
}
 
Example 9
Source File: Producer.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    String topic = TOPIC_ENV == null ? "TopicTest" : TOPIC_ENV;
    int count = COUNT_ENV == null ? 1000 : Integer.valueOf(COUNT_ENV);
    long term = System.currentTimeMillis();


    /*
     * Instantiate with a producer group name.
     */
    DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");

    /*
     * Specify name server addresses.
     * <p/>
     *
     * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR
     * <pre>
     * {@code
     * producer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876");
     * }
     * </pre>
     */

    /*
     * Launch the instance.
     */
    producer.start();

    for (int i = 0; i < count; i++) {
        try {

            /*
             * Create a message instance, specifying topic, tag and message body.
             */
            Message msg = new Message(topic /* Topic */,
                "TagA" /* Tag */,
                ("Hello RocketMQ:" + i + ":" + term).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );

            /*
             * Call send message to deliver message to one of brokers.
             */
            SendResult sendResult = producer.send(msg);
            if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
                System.out.printf("send ok:%s%n", new String(msg.getBody()));
            }

            System.out.printf("%s%n", sendResult);
        } catch (Exception e) {
            e.printStackTrace();
            Thread.sleep(1000);
        }
    }

    /*
     * Shut down once the producer instance is not longer in use.
     */
    producer.shutdown();
}
 
Example 10
Source File: Utils.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public static void checkSend(String cluster, String nameSvr, String address) throws MQClientException, NoSuchFieldException,
        SecurityException, InterruptedException, IllegalArgumentException, IllegalAccessException, UnsupportedEncodingException, MQBrokerException, RemotingException {

    if (!isBrokerTopicWritable(cluster, nameSvr, address)) {
        return;
    }

    DefaultMQProducer producer = getSendCheckProducer(nameSvr, cluster, address);
    MQClientInstance instance = producer.getDefaultMQProducerImpl().getmQClientFactory();
    Field f = MQClientInstance.class.getDeclaredField("brokerAddrTable");
    f.setAccessible(true);

    Field f2 = MQClientInstance.class.getDeclaredField("scheduledExecutorService");
    f2.setAccessible(true);

    ScheduledExecutorService service = (ScheduledExecutorService) f2.get(instance);
    service.shutdown();
    service.awaitTermination(1000, TimeUnit.SECONDS);

    ConcurrentHashMap<String, HashMap<Long, String>> map = (ConcurrentHashMap<String, HashMap<Long, String>>) f
            .get(instance);
    HashMap<Long, String> addresses = new HashMap<>();
    addresses.put(0L, address);
    map.put("rmqmonitor_" + address, addresses);

    MessageQueue queue = new MessageQueue("SELF_TEST_TOPIC", "rmqmonitor_" + address, 0);
    boolean sendOk = false;
    SendResult sendResult = null;
    for (int i = 0; i < 2; i++) {
        try {
            Message msg = new Message("SELF_TEST_TOPIC", // topic
                    "TagA", // tag
                    ("Hello RocketMQ " + i).getBytes()// body
            );
            sendResult = producer.send(msg, queue);
            if (sendResult.getSendStatus() == SendStatus.SEND_OK || sendResult.getSendStatus() == SLAVE_NOT_AVAILABLE) {
                sendOk = true;
                break;
            }

            logger.warn("send result failed, SendResult={}, cluster={}, namesvr={}, address={}", sendResult, cluster, nameSvr, address);
        } catch (Exception e) {
            logger.error("send exception, cluster={}, namesvr={}, address={}", cluster, nameSvr, address, e);
        }
        Thread.sleep(1000);
    }

    // 报警
    if (!sendOk) {
        logger.error(String.format("[AlarmSendErr] cluster=%s, broker=%s, result=%s", cluster, address, sendResult == null ? "null" : sendResult.toString()));
    } else {
        logger.info("AlarmSendCheck cluster={}, broker={}, result={}", cluster, address, sendResult.toString());
    }
}
 
Example 11
Source File: Producer.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    String topic = TOPIC_ENV == null ? "TopicTest" : TOPIC_ENV;
    int count = COUNT_ENV == null ? 1000 : Integer.valueOf(COUNT_ENV);
    long term = System.currentTimeMillis();


    /*
     * Instantiate with a producer group name.
     */
    DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");

    /*
     * Specify name server addresses.
     * <p/>
     *
     * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR
     * <pre>
     * {@code
     * producer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876");
     * }
     * </pre>
     */

    /*
     * Launch the instance.
     */
    producer.start();

    for (int i = 0; i < count; i++) {
        try {

            /*
             * Create a message instance, specifying topic, tag and message body.
             */
            Message msg = new Message(topic /* Topic */,
                "TagA" /* Tag */,
                ("Hello RocketMQ:" + i + ":" + term).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );

            /*
             * Call send message to deliver message to one of brokers.
             */
            SendResult sendResult = producer.send(msg);
            if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
                System.out.printf("send ok:%s%n", new String(msg.getBody()));
            }

            System.out.printf("%s%n", sendResult);
        } catch (Exception e) {
            e.printStackTrace();
            Thread.sleep(1000);
        }
    }

    /*
     * Shut down once the producer instance is not longer in use.
     */
    producer.shutdown();
}
 
Example 12
Source File: MQClientAPIImpl.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
private SendResult processSendResponse(
    final String brokerName,
    final Message msg,
    final RemotingCommand response
) throws MQBrokerException, RemotingCommandException {
    SendStatus sendStatus;
    switch (response.getCode()) {
        case ResponseCode.FLUSH_DISK_TIMEOUT: {
            sendStatus = SendStatus.FLUSH_DISK_TIMEOUT;
            break;
        }
        case ResponseCode.FLUSH_SLAVE_TIMEOUT: {
            sendStatus = SendStatus.FLUSH_SLAVE_TIMEOUT;
            break;
        }
        case ResponseCode.SLAVE_NOT_AVAILABLE: {
            sendStatus = SendStatus.SLAVE_NOT_AVAILABLE;
            break;
        }
        case ResponseCode.SUCCESS: {
            sendStatus = SendStatus.SEND_OK;
            break;
        }
        default: {
            throw new MQBrokerException(response.getCode(), response.getRemark());
        }
    }

    SendMessageResponseHeader responseHeader =
            (SendMessageResponseHeader) response.decodeCommandCustomHeader(SendMessageResponseHeader.class);

    //If namespace not null , reset Topic without namespace.
    String topic = msg.getTopic();
    if (StringUtils.isNotEmpty(this.clientConfig.getNamespace())) {
        topic = NamespaceUtil.withoutNamespace(topic, this.clientConfig.getNamespace());
    }

    MessageQueue messageQueue = new MessageQueue(topic, brokerName, responseHeader.getQueueId());

    String uniqMsgId = MessageClientIDSetter.getUniqID(msg);
    if (msg instanceof MessageBatch) {
        StringBuilder sb = new StringBuilder();
        for (Message message : (MessageBatch) msg) {
            sb.append(sb.length() == 0 ? "" : ",").append(MessageClientIDSetter.getUniqID(message));
        }
        uniqMsgId = sb.toString();
    }
    SendResult sendResult = new SendResult(sendStatus,
            uniqMsgId,
            responseHeader.getMsgId(), messageQueue, responseHeader.getQueueOffset());
    sendResult.setTransactionId(responseHeader.getTransactionId());
    String regionId = response.getExtFields().get(MessageConst.PROPERTY_MSG_REGION);
    String traceOn = response.getExtFields().get(MessageConst.PROPERTY_TRACE_SWITCH);
    if (regionId == null || regionId.isEmpty()) {
        regionId = MixAll.DEFAULT_TRACE_REGION_ID;
    }
    if (traceOn != null && traceOn.equals("false")) {
        sendResult.setTraceOn(false);
    } else {
        sendResult.setTraceOn(true);
    }
    sendResult.setRegionId(regionId);
    return sendResult;
}