rocketmq 中SendCallback有效性检查

Java Code Examples for com.alibaba.rocketmq.client.producer.SendCallback
The following are top voted examples for showing how to use com.alibaba.rocketmq.client.producer.SendCallback. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.

Example 1
Project: coca   File: TestProducer.java   View source code	6 votes	vote down vote up
@Test
public void testAsyncProducer() throws Exception {
    // Instantiate with a producer group name.
    DefaultMQProducer producer = new DefaultMQProducer("ExampleProducerGroup");
    // Launch the instance.
    producer.start();
    producer.setRetryTimesWhenSendAsyncFailed(0);
    for (int i = 0; i < 100; i++) {
        final int index = i;
        // Create a message instance, specifying topic, tag and message body.
        Message msg = new Message("TopicTest", "TagA", "OrderID188", "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
        producer.send(msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.printf("%-10d OK %s %n", index, sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable e) {
                System.out.printf("%-10d Exception %s %n", index, e);
                e.printStackTrace();
            }
        });
    }
}

Example 2

Project: rocketmq-all-trans   File: DefaultMQProducerImpl.java   View source code	6 votes	vote down vote up
/**
 * KERNEL ASYNC -------------------------------------------------------
 */
public void send(Message msg, MessageQueue mq, SendCallback sendCallback) throws MQClientException,
        RemotingException, InterruptedException {
    // 有效性检查
    this.makeSureStateOK();
    Validators.checkMessage(msg, this.defaultMQProducer);

    if (!msg.getTopic().equals(mq.getTopic())) {
        throw new MQClientException("message's topic not equal mq's topic", null);
    }

    try {
        this.sendKernelImpl(msg, mq, CommunicationMode.ASYNC, sendCallback);
    }
    catch (MQBrokerException e) {
        throw new MQClientException("unknow exception", e);
    }
}

Example 3

Project: RocketMQ-3.0.8   File: DefaultMQProducerImpl.java   View source code	6 votes	vote down vote up
/**
 * KERNEL ASYNC -------------------------------------------------------
 */
public void send(Message msg, MessageQueue mq, SendCallback sendCallback) throws MQClientException,
        RemotingException, InterruptedException {
    // 有效性检查
    this.makeSureStateOK();
    Validators.checkMessage(msg, this.defaultMQProducer);

    if (!msg.getTopic().equals(mq.getTopic())) {
        throw new MQClientException("message's topic not equal mq's topic", null);
    }

    try {
        this.sendKernelImpl(msg, mq, CommunicationMode.ASYNC, sendCallback);
    }
    catch (MQBrokerException e) {
        throw new MQClientException("unknow exception", e);
    }
}

Example 4

Project: reading-and-annotate-rocketmq-3.4.6   File: MQClientAPIImpl.java   View source code	5 votes	vote down vote up
public SendResult sendMessage(//
        final String addr,// 1
        final String brokerName,// 2
        final Message msg,// 3
        final SendMessageRequestHeader requestHeader,// 4
        final long timeoutMillis,// 5
        final CommunicationMode communicationMode,// 6
        final SendCallback sendCallback// 7
) throws RemotingException, MQBrokerException, InterruptedException {
    RemotingCommand request = null;
    if (sendSmartMsg) {
        SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);
        request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE_V2, requestHeaderV2);
    }
    else { //组装头部信息
        request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, requestHeader);
    }

    request.setBody(msg.getBody()); //包体body信息赋值

    switch (communicationMode) {
    case ONEWAY:
        this.remotingClient.invokeOneway(addr, request, timeoutMillis);
        return null;
    case ASYNC:
        this.sendMessageAsync(addr, brokerName, msg, timeoutMillis, request, sendCallback);
        return null;
    case SYNC:
        return this.sendMessageSync(addr, brokerName, msg, timeoutMillis, request);
    default:
        assert false;
        break;
    }

    return null;
}

Example 5

Project: reading-and-annotate-rocketmq-3.4.6   File: MQClientAPIImpl.java   View source code	5 votes	vote down vote up
private void sendMessageAsync(//
        final String addr,//
        final String brokerName,//
        final Message msg,//
        final long timeoutMillis,//
        final RemotingCommand request,//
        final SendCallback sendCallback//
) throws RemotingException, InterruptedException {
    this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
        @Override
        public void operationComplete(ResponseFuture responseFuture) {
            if (null == sendCallback)
                return;

            RemotingCommand response = responseFuture.getResponseCommand();
            if (response != null) {
                try {
                    SendResult sendResult = MQClientAPIImpl.this.processSendResponse(brokerName, msg, response);
                    assert sendResult != null;
                    sendCallback.onSuccess(sendResult);
                }
                catch (Exception e) {
                    sendCallback.onException(e);
                }
            }
            else {
                if (!responseFuture.isSendRequestOK()) {
                    sendCallback.onException(new MQClientException("send request failed", responseFuture.getCause()));
                }
                else if (responseFuture.isTimeout()) {
                    sendCallback.onException(new MQClientException("wait response timeout " + responseFuture.getTimeoutMillis() + "ms",
                        responseFuture.getCause()));
                }
                else {
                    sendCallback.onException(new MQClientException("unknow reseaon", responseFuture.getCause()));
                }
            }
        }
    });
}

Example 6

Project: coca   File: RMQGroupChannel.java   View source code	5 votes	vote down vote up
private void send(Message msg, PacketFuture pf) throws Exception {
    producer.send(msg, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            LOG.info(sendResult.toString());
            pf.result(new PacketResult(PacketResult.IOSt.SEND_SUCC));
        }

        @Override
        public void onException(Throwable e) {
            LOG.error(e.getMessage(), e);
            pf.result(new PacketResult(PacketResult.IOSt.SEND_FAIL));
        }
    });
}

Example 7

Project: rocketmq-commet   File: MQClientAPIImpl.java   View source code	5 votes	vote down vote up
private void sendMessageAsync(//
                              final String addr,//
                              final String brokerName,//
                              final Message msg,//
                              final long timeoutMillis,//
                              final RemotingCommand request,//
                              final SendCallback sendCallback//
) throws RemotingException, InterruptedException {
    this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
        @Override
        public void operationComplete(ResponseFuture responseFuture) {
            if (null == sendCallback)
                return;

            RemotingCommand response = responseFuture.getResponseCommand();
            if (response != null) {
                try {
                    SendResult sendResult = MQClientAPIImpl.this.processSendResponse(brokerName, msg, response);
                    assert sendResult != null;
                    sendCallback.onSuccess(sendResult);
                } catch (Exception e) {
                    sendCallback.onException(e);
                }
            } else {
                if (!responseFuture.isSendRequestOK()) {
                    sendCallback.onException(new MQClientException("send request failed", responseFuture.getCause()));
                } else if (responseFuture.isTimeout()) {
                    sendCallback.onException(new MQClientException("wait response timeout " + responseFuture.getTimeoutMillis() + "ms",
                            responseFuture.getCause()));
                } else {
                    sendCallback.onException(new MQClientException("unknow reseaon", responseFuture.getCause()));
                }
            }
        }
    });
}

Example 8

Project: rocketmq-all-trans   File: DefaultMQProducerImpl.java   View source code	5 votes	vote down vote up
/**
 * DEFAULT ASYNC -------------------------------------------------------
 */
public void send(Message msg, SendCallback sendCallback) throws MQClientException, RemotingException,
        InterruptedException {
    try {
        this.sendDefaultImpl(msg, CommunicationMode.ASYNC, sendCallback);
    }
    catch (MQBrokerException e) {
        throw new MQClientException("unknow exception", e);
    }
}

Example 9

Project: rocketmq-all-trans   File: DefaultMQProducerImpl.java   View source code	5 votes	vote down vote up
private SendResult sendSelectImpl(//
        Message msg,//
        MessageQueueSelector selector,//
        Object arg,//
        final CommunicationMode communicationMode,//
        final SendCallback sendCallback//
) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    // 有效性检查
    this.makeSureStateOK();
    Validators.checkMessage(msg, this.defaultMQProducer);

    TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
    if (topicPublishInfo != null && topicPublishInfo.ok()) {
        MessageQueue mq = null;
        try {
            mq = selector.select(topicPublishInfo.getMessageQueueList(), msg, arg);
        }
        catch (Throwable e) {
            throw new MQClientException("select message queue throwed exception.", e);
        }

        if (mq != null) {
            return this.sendKernelImpl(msg, mq, communicationMode, sendCallback);
        }
        else {
            throw new MQClientException("select message queue return null.", null);
        }
    }

    throw new MQClientException("No route info for this topic, " + msg.getTopic(), null);
}

Example 10

Project: rocketmq-all-trans   File: DefaultMQProducerImpl.java   View source code	5 votes	vote down vote up
/**
 * SELECT ASYNC -------------------------------------------------------
 */
public void send(Message msg, MessageQueueSelector selector, Object arg, SendCallback sendCallback)
        throws MQClientException, RemotingException, InterruptedException {
    try {
        this.sendSelectImpl(msg, selector, arg, CommunicationMode.ASYNC, sendCallback);
    }
    catch (MQBrokerException e) {
        throw new MQClientException("unknow exception", e);
    }
}

Example 11

Project: rocketmq-all-trans   File: MQClientAPIImpl.java   View source code	5 votes	vote down vote up
/**
 * 发送消息
 */
public SendResult sendMessage(//
        final String addr,// 1
        final String brokerName,// 2
        final Message msg,// 3
        final SendMessageRequestHeader requestHeader,// 4
        final long timeoutMillis,// 5
        final CommunicationMode communicationMode,// 6
        final SendCallback sendCallback// 7
) throws RemotingException, MQBrokerException, InterruptedException {
    // 添加虚拟运行环境相关的projectGroupPrefix
    if (!UtilAll.isBlank(projectGroupPrefix)) {
        msg.setTopic(VirtualEnvUtil.buildWithProjectGroup(msg.getTopic(), projectGroupPrefix));
        requestHeader.setProducerGroup(VirtualEnvUtil.buildWithProjectGroup(
            requestHeader.getProducerGroup(), projectGroupPrefix));
        requestHeader.setTopic(VirtualEnvUtil.buildWithProjectGroup(requestHeader.getTopic(),
            projectGroupPrefix));
    }

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

    request.setBody(msg.getBody());

    switch (communicationMode) {
    case ONEWAY:
        this.remotingClient.invokeOneway(addr, request, timeoutMillis);
        return null;
    case ASYNC:
        this.sendMessageAsync(addr, brokerName, msg, timeoutMillis, request, sendCallback);
        return null;
    case SYNC:
        return this.sendMessageSync(addr, brokerName, msg, timeoutMillis, request);
    default:
        assert false;
        break;
    }

    return null;
}

Example 12

Project: RocketMQ-3.0.8   File: DefaultMQProducerImpl.java   View source code	5 votes	vote down vote up
/**
 * DEFAULT ASYNC -------------------------------------------------------
 */
public void send(Message msg, SendCallback sendCallback) throws MQClientException, RemotingException,
        InterruptedException {
    try {
        this.sendDefaultImpl(msg, CommunicationMode.ASYNC, sendCallback);
    }
    catch (MQBrokerException e) {
        throw new MQClientException("unknow exception", e);
    }
}

Example 13

Project: RocketMQ-3.0.8   File: DefaultMQProducerImpl.java   View source code	5 votes	vote down vote up
private SendResult sendSelectImpl(//
        Message msg,//
        MessageQueueSelector selector,//
        Object arg,//
        final CommunicationMode communicationMode,//
        final SendCallback sendCallback//
) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    // 有效性检查
    this.makeSureStateOK();
    Validators.checkMessage(msg, this.defaultMQProducer);

    TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
    if (topicPublishInfo != null && topicPublishInfo.ok()) {
        MessageQueue mq = null;
        try {
            mq = selector.select(topicPublishInfo.getMessageQueueList(), msg, arg);
        }
        catch (Throwable e) {
            throw new MQClientException("select message queue throwed exception.", e);
        }

        if (mq != null) {
            return this.sendKernelImpl(msg, mq, communicationMode, sendCallback);
        }
        else {
            throw new MQClientException("select message queue return null.", null);
        }
    }

    throw new MQClientException("No route info for this topic, " + msg.getTopic(), null);
}

Example 14

Project: RocketMQ-3.0.8   File: DefaultMQProducerImpl.java   View source code	5 votes	vote down vote up
/**
 * SELECT ASYNC -------------------------------------------------------
 */
public void send(Message msg, MessageQueueSelector selector, Object arg, SendCallback sendCallback)
        throws MQClientException, RemotingException, InterruptedException {
    try {
        this.sendSelectImpl(msg, selector, arg, CommunicationMode.ASYNC, sendCallback);
    }
    catch (MQBrokerException e) {
        throw new MQClientException("unknow exception", e);
    }
}

Example 15

Project: RocketMQ-3.0.8   File: MQClientAPIImpl.java   View source code	5 votes	vote down vote up
/**
 * 发送消息
 */
public SendResult sendMessage(//
        final String addr,// 1
        final String brokerName,// 2
        final Message msg,// 3
        final SendMessageRequestHeader requestHeader,// 4
        final long timeoutMillis,// 5
        final CommunicationMode communicationMode,// 6
        final SendCallback sendCallback// 7
) throws RemotingException, MQBrokerException, InterruptedException {
    // 添加虚拟运行环境相关的projectGroupPrefix
    if (!UtilAll.isBlank(projectGroupPrefix)) {
        msg.setTopic(VirtualEnvUtil.buildWithProjectGroup(msg.getTopic(), projectGroupPrefix));
        requestHeader.setProducerGroup(VirtualEnvUtil.buildWithProjectGroup(
            requestHeader.getProducerGroup(), projectGroupPrefix));
        requestHeader.setTopic(VirtualEnvUtil.buildWithProjectGroup(requestHeader.getTopic(),
            projectGroupPrefix));
    }

    RemotingCommand request =
            RemotingCommand.createRequestCommand(MQRequestCode.SEND_MESSAGE_VALUE, requestHeader);
    request.setBody(msg.getBody());

    switch (communicationMode) {
    case ONEWAY:
        this.remotingClient.invokeOneway(addr, request, timeoutMillis);
        return null;
    case ASYNC:
        this.sendMessageAsync(addr, brokerName, msg, timeoutMillis, request, sendCallback);
        return null;
    case SYNC:
        return this.sendMessageSync(addr, brokerName, msg, timeoutMillis, request);
    default:
        assert false;
        break;
    }

    return null;
}

Example 16

Project: rocketmq-commet   File: MQClientAPIImpl.java   View source code	4 votes	vote down vote up
/**
 * 发送消息到Broker
 *
 * @param addr              broker地址
 * @param brokerName
 * @param msg
 * @param requestHeader
 * @param timeoutMillis
 * @param communicationMode
 * @param sendCallback
 * @return
 * @throws RemotingException
 * @throws MQBrokerException
 * @throws InterruptedException
 */
public SendResult sendMessage(//
                              final String addr,// 1
                              final String brokerName,// 2
                              final Message msg,// 3
                              final SendMessageRequestHeader requestHeader,// 4
                              final long timeoutMillis,// 5
                              final CommunicationMode communicationMode,// 6
                              final SendCallback sendCallback// 7
) throws RemotingException, MQBrokerException, InterruptedException {

    RemotingCommand request = null;
    /**
     * send smart msg?
     * 作用是啥?
     */
    if (sendSmartMsg) {
        SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);
        request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE_V2, requestHeaderV2);
    } else {
        request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, requestHeader);
    }

    request.setBody(msg.getBody());

    switch (communicationMode) {
        case ONEWAY:
            this.remotingClient.invokeOneway(addr, request, timeoutMillis);
            return null;
        case ASYNC:
            this.sendMessageAsync(addr, brokerName, msg, timeoutMillis, request, sendCallback);
            return null;
        case SYNC:
            return this.sendMessageSync(addr, brokerName, msg, timeoutMillis, request);
        default:
            assert false;
            break;
    }

    return null;
}

Example 17

Project: rocketmq-all-trans   File: MQClientAPIImpl.java   View source code	4 votes	vote down vote up
private void sendMessageAsync(//
        final String addr,//
        final String brokerName,//
        final Message msg,//
        final long timeoutMillis,//
        final RemotingCommand request,//
        final SendCallback sendCallback//
) throws RemotingException, InterruptedException {
    this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
        @Override
        public void operationComplete(ResponseFuture responseFuture) {
            if (null == sendCallback)
                return;

            RemotingCommand response = responseFuture.getResponseCommand();
            if (response != null) {
                try {
                    SendResult sendResult =
                            MQClientAPIImpl.this.processSendResponse(brokerName, msg, response);
                    assert sendResult != null;
                    sendCallback.onSuccess(sendResult);
                }
                catch (Exception e) {
                    sendCallback.onException(e);
                }
            }
            else {
                if (!responseFuture.isSendRequestOK()) {
                    sendCallback.onException(new MQClientException("send request failed", responseFuture
                        .getCause()));
                }
                else if (responseFuture.isTimeout()) {
                    sendCallback.onException(new MQClientException("wait response timeout "
                            + responseFuture.getTimeoutMillis() + "ms", responseFuture.getCause()));
                }
                else {
                    sendCallback.onException(new MQClientException("unknow reseaon", responseFuture
                        .getCause()));
                }
            }
        }
    });
}

Example 18

Project: RocketMQ-3.0.8   File: MQClientAPIImpl.java   View source code	4 votes	vote down vote up
private void sendMessageAsync(//
        final String addr,//
        final String brokerName,//
        final Message msg,//
        final long timeoutMillis,//
        final RemotingCommand request,//
        final SendCallback sendCallback//
) throws RemotingException, InterruptedException {
    this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
        @Override
        public void operationComplete(ResponseFuture responseFuture) {
            if (null == sendCallback)
                return;

            RemotingCommand response = responseFuture.getResponseCommand();
            if (response != null) {
                try {
                    SendResult sendResult =
                            MQClientAPIImpl.this.processSendResponse(brokerName, msg, response);
                    assert sendResult != null;
                    sendCallback.onSuccess(sendResult);
                }
                catch (Exception e) {
                    sendCallback.onException(e);
                }
            }
            else {
                if (!responseFuture.isSendRequestOK()) {
                    sendCallback.onException(new MQClientException("send request failed", responseFuture
                        .getCause()));
                }
                else if (responseFuture.isTimeout()) {
                    sendCallback.onException(new MQClientException("wait response timeout "
                            + responseFuture.getTimeoutMillis() + "ms", responseFuture.getCause()));
                }
                else {
                    sendCallback.onException(new MQClientException("unknow reseaon", responseFuture
                        .getCause()));
                }
            }
        }
    });
}

Example 19

Project: flume-rocketmq-sink   File: RocketMQSink.java   View source code	2 votes	vote down vote up
private SendCallback createDefaultSendCallback(){
	
	return new DefaultSendCallback();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RocketMQ提供了异步发送消息的功能,可以实现消息的异步解耦。\[2\]通过使用org.apache.rocketmq.client.producer.DefaultMQProducer#send方法,并传入一个SendCallback回调函数,可以实现异步发送消息。在发送消息时,可以指定一个回调函数,当消息发送成功或失败时,会调用该回调函数进行相应的处理。 要使用RocketMQ进行异步解耦,首先需要将RocketMQ的zip包上传到服务器,并解压。\[3\]然后,可以根据自己的需求进行配置和管理RocketMQ。可以使用命令解压zip包,并将解压后的目录重命名,以方便管理。 通过使用RocketMQ的异步发送功能,可以实现消息的异步解耦,将消息发送到消息队列,然后由消费者进行消费。这样可以实现解耦,提高系统的可扩展性和可靠性。 #### 引用[.reference_title] - *1* *2* [高并发异步解耦利器:RocketMQ究竟强在哪里?](https://blog.csdn.net/liangwenmail/article/details/121537666)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [阿里我来了,RocketMQ扫盲!](https://blog.csdn.net/weixin_43896643/article/details/118737002)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值