io.openmessaging.producer.SendResult Java Examples

The following examples show how to use io.openmessaging.producer.SendResult. 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: ProducerImpl.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
private SendResult send(final Message message, long timeout) {
    checkMessageType(message);
    org.apache.rocketmq.common.message.Message rmqMessage = msgConvert((BytesMessage) message);
    try {
        org.apache.rocketmq.client.producer.SendResult rmqResult = this.rocketmqProducer.send(rmqMessage, timeout);
        if (!rmqResult.getSendStatus().equals(SendStatus.SEND_OK)) {
            log.error(String.format("Send message to RocketMQ failed, %s", message));
            throw new OMSRuntimeException("-1", "Send message to RocketMQ broker failed.");
        }
        message.sysHeaders().put(Message.BuiltinKeys.MESSAGE_ID, rmqResult.getMsgId());
        return OMSUtil.sendResultConvert(rmqResult);
    } catch (Exception e) {
        log.error(String.format("Send message to RocketMQ failed, %s", message), e);
        throw checkProducerException(rmqMessage.getTopic(), message.sysHeaders().getString(Message.BuiltinKeys.MESSAGE_ID), e);
    }
}
 
Example #2
Source File: ProducerImpl.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
private SendResult send(final Message message, long timeout) {
    checkMessageType(message);
    org.apache.rocketmq.common.message.Message rmqMessage = msgConvert((BytesMessage) message);
    try {
        org.apache.rocketmq.client.producer.SendResult rmqResult = this.rocketmqProducer.send(rmqMessage, timeout);
        if (!rmqResult.getSendStatus().equals(SendStatus.SEND_OK)) {
            log.error(String.format("Send message to RocketMQ failed, %s", message));
            throw new OMSRuntimeException("-1", "Send message to RocketMQ broker failed.");
        }
        message.sysHeaders().put(Message.BuiltinKeys.MESSAGE_ID, rmqResult.getMsgId());
        return OMSUtil.sendResultConvert(rmqResult);
    } catch (Exception e) {
        log.error(String.format("Send message to RocketMQ failed, %s", message), e);
        throw checkProducerException(rmqMessage.getTopic(), message.sysHeaders().getString(Message.BuiltinKeys.MESSAGE_ID), e);
    }
}
 
Example #3
Source File: BrokerBasedLog.java    From openmessaging-connect-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void send(K key, V value){

    try {
        byte[] messageBody = encodeKeyValue(key, value);
        if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
            log.error("Message size is greater than {} bytes, key: {}, value {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, key, value);
            return;
        }
        Future<SendResult> result = producer.sendAsync(producer.createBytesMessage(queueName, messageBody));
        result.addListener((future) -> {

            if (future.getThrowable() != null) {
                log.error("Send async message Failed, error: {}", future.getThrowable());
            } else {
                log.info("Send async message OK, msgId: {}", future.get().messageId() + "\n");
            }
        });
    } catch (Exception e) {
        log.error("BrokerBaseLog send async message Failed.", e);
    }
}
 
Example #4
Source File: SimpleMetadata.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    KeyValue keyValue = OMS.newKeyValue();
    keyValue.put(OMSBuiltinKeys.ACCOUNT_KEY, "test_token");

    MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint("oms:joyqueue://[email protected]:50088/UNKNOWN", keyValue);

    Producer producer = messagingAccessPoint.createProducer();
    producer.start();

    QueueMetaData queueMetaData = producer.getQueueMetaData("test_topic_0");
    for (QueueMetaData.Partition partition : queueMetaData.partitions()) {
        System.out.println(String.format("partition: %s, partitionHost: %s", partition.partitionId(), partition.partitonHost()));
    }

    Message message = producer.createMessage("test_topic_0", "body".getBytes());

    SendResult sendResult = producer.send(message);
    System.out.println(String.format("messageId: %s", sendResult.messageId()));
}
 
Example #5
Source File: AsyncBatchProducer.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
        KeyValue keyValue = OMS.newKeyValue();
        keyValue.put(OMSBuiltinKeys.ACCOUNT_KEY, "test_token");

        MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint("oms:joyqueue://[email protected]:50088/UNKNOWN", keyValue);

        Producer producer = messagingAccessPoint.createProducer();
        producer.start();

        List<Message> messages = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            Message message = producer.createMessage("test_topic_0", "body".getBytes());
            messages.add(message);
        }

        Future<SendResult> future = producer.sendAsync(messages);

//        future.addListener(new FutureListener<SendResult>() {
//            @Override
//            public void operationComplete(Future<SendResult> future) {
//                System.out.println(future.get().messageId());
//            }
//        });
        System.out.println(future.get().messageId());
    }
 
Example #6
Source File: ProducerImpl.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
private SendResult send(final Message message, long timeout) {
    checkMessageType(message);
    org.apache.rocketmq.common.message.Message rmqMessage = msgConvert((BytesMessage) message);
    try {
        org.apache.rocketmq.client.producer.SendResult rmqResult = this.rocketmqProducer.send(rmqMessage, timeout);
        if (!rmqResult.getSendStatus().equals(SendStatus.SEND_OK)) {
            log.error(String.format("Send message to RocketMQ failed, %s", message));
            throw new OMSRuntimeException("-1", "Send message to RocketMQ broker failed.");
        }
        message.sysHeaders().put(Message.BuiltinKeys.MESSAGE_ID, rmqResult.getMsgId());
        return OMSUtil.sendResultConvert(rmqResult);
    } catch (Exception e) {
        log.error(String.format("Send message to RocketMQ failed, %s", message), e);
        throw checkProducerException(rmqMessage.getTopic(), message.sysHeaders().getString(Message.BuiltinKeys.MESSAGE_ID), e);
    }
}
 
Example #7
Source File: AsyncProducer.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        KeyValue keyValue = OMS.newKeyValue();
        keyValue.put(OMSBuiltinKeys.ACCOUNT_KEY, "test_token");
        keyValue.put(JoyQueueBuiltinKeys.TRANSACTION_TIMEOUT, 1000 * 10);

        MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint("oms:joyqueue://[email protected]:50088/UNKNOWN", keyValue);

        Producer producer = messagingAccessPoint.createProducer();
        producer.start();

        Message message = producer.createMessage("test_topic_0", "body".getBytes());
        Future<SendResult> future = producer.sendAsync(message);

//        future.addListener(new FutureListener<SendResult>() {
////            @Override
////            public void operationComplete(Future<SendResult> future) {
////                System.out.println(future.get().messageId());
////            }
////        });

        System.out.println(future.get().messageId());
    }
 
Example #8
Source File: ExtensionTransactionProducer.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
        KeyValue keyValue = OMS.newKeyValue();
        keyValue.put(OMSBuiltinKeys.ACCOUNT_KEY, "test_token");

        MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint("oms:joyqueue://[email protected]:50088/UNKNOWN", keyValue);

        ExtensionProducer extensionProducer = (ExtensionProducer) messagingAccessPoint.createProducer();
        extensionProducer.start();

        ExtensionTransactionalResult transactionalResult = extensionProducer.prepare();

        for (int i = 0; i < 10; i++) {
            // 可以发多条事务消息
            Message message = extensionProducer.createMessage("test_topic_0", "body".getBytes());

            // 添加事务id,设置过事务id的才会被补偿,补偿时会带上这个事务id,非必填
            // 建议根据业务使用有意义的事务id
            message.extensionHeader().get().setTransactionId("test_transactionId");

            SendResult sendResult = transactionalResult.send(message);
            System.out.println(sendResult.messageId());
        }

        // 提交事务
        transactionalResult.commit();

        // 回滚事务
//        transactionalResult.rollback();
    }
 
Example #9
Source File: ExtensionTransactionalResultAdapter.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public List<SendResult> send(List<Message> messages) {
    try {
        Preconditions.checkArgument(CollectionUtils.isNotEmpty(messages), "messages can not be null");

        List<ProduceMessage> produceMessages = checkAndConvertMessage(messages);
        List<org.joyqueue.client.internal.producer.domain.SendResult> sendResults = transactionMessageProducer.batchSend(produceMessages);
        return SendResultConverter.convert(sendResults);
    } catch (Throwable cause) {
        throw ExceptionConverter.convertProduceException(cause);
    }
}
 
Example #10
Source File: ExtensionTransactionalResultAdapter.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public SendResult send(Message message) {
    try {
        Preconditions.checkArgument(message instanceof MessageAdapter, "message is not supported");

        MessageAdapter messageAdapter = (MessageAdapter) message;
        org.joyqueue.client.internal.producer.domain.SendResult sendResult = transactionMessageProducer.send(messageAdapter.getProduceMessage());
        return SendResultConverter.convert(sendResult);
    } catch (Throwable cause) {
        throw ExceptionConverter.convertProduceException(cause);
    }
}
 
Example #11
Source File: ProducerImpl.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public void sendOneway(Message message) {
    try {
        Preconditions.checkArgument(message instanceof MessageAdapter, "message is not supported");

        FutureAdapter<SendResult> future = new FutureAdapter<>();
        MessageAdapter messageAdapter = (MessageAdapter) message;
        messageProducer.sendOneway(messageAdapter.getProduceMessage());
    } catch (Throwable cause) {
        throw handleProduceException(cause);
    }
}
 
Example #12
Source File: ProducerImpl.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public SendResult send(Message message) {
    try {
        Preconditions.checkArgument(message instanceof MessageAdapter, "message is not supported");

        MessageAdapter messageAdapter = (MessageAdapter) message;
        org.joyqueue.client.internal.producer.domain.SendResult sendResult = messageProducer.send(messageAdapter.getProduceMessage());
        return SendResultConverter.convert(sendResult);
    } catch (Throwable cause) {
        throw handleProduceException(cause);
    }
}
 
Example #13
Source File: SendResultConverter.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static List<SendResult> convert(List<org.joyqueue.client.internal.producer.domain.SendResult> sendResults) {
    List<SendResult> result = Lists.newArrayListWithCapacity(sendResults.size());
    for (org.joyqueue.client.internal.producer.domain.SendResult sendResult : sendResults) {
        result.add(convert(sendResult));
    }
    return result;
}
 
Example #14
Source File: SpringMain.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-sample.xml");
    Producer producer = (Producer) applicationContext.getBean("producer1");

    for (int i = 0; i < 10; i++) {
        Message message = producer.createMessage("test_topic_0", "test".getBytes());
        SendResult sendResult = producer.send(message);
        logger.info("Message ID: {}", sendResult.messageId());
    }
}
 
Example #15
Source File: SpringBootMain.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    for (int i = 0; i < 10; i++) {
        Message message = producer.createMessage("test_topic_0", "test".getBytes());
        SendResult sendResult = producer.send(message);
        logger.info("sendResult: {}", sendResult);
    }
}
 
Example #16
Source File: WorkerSourceTask.java    From openmessaging-connect-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Send list of sourceDataEntries to MQ.
 * @param sourceDataEntries
 */
private void sendRecord(Collection<SourceDataEntry> sourceDataEntries) {

    for(SourceDataEntry sourceDataEntry : sourceDataEntries){
        ByteBuffer partition = sourceDataEntry.getSourcePartition();
        ByteBuffer position = sourceDataEntry.getSourcePosition();
        sourceDataEntry.setSourcePartition(null);
        sourceDataEntry.setSourcePosition(null);
        byte[] payload = recordConverter.objectToByte(sourceDataEntry.getPayload());
        Object[] newPayload = new Object[1];
        newPayload[0] = Base64.getEncoder().encodeToString(payload);
        sourceDataEntry.setPayload(newPayload);
        final byte[] messageBody = JSON.toJSONString(sourceDataEntry).getBytes();
        if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
            log.error("Send record, message size is greater than {} bytes, payload: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, sourceDataEntry.getPayload());
            return;
        }
        Message sourceMessage = producer.createBytesMessage(sourceDataEntry.getQueueName(), messageBody);
        Future<SendResult> sendResult = producer.sendAsync(sourceMessage);
        sendResult.addListener((future) -> {

            if(null != future.getThrowable()){
                log.error("Source task send record failed.", future.getThrowable());
            }else{
                try {
                    // send ok

                    if(null != partition && null != position){
                        positionData.put(partition, position);
                    }
                } catch (Exception e) {
                    log.error("Source task save position info failed.", e);
                }
            }
        });
    }
}
 
Example #17
Source File: SimpleProducer.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        final String app = "test_app";
        final String token = "some token";
        final String dataCenter = "default";
        final String brokerAddr = "127.0.0.1:50088";
        final String topic = "test_topic_0";
        // oms:joyqueue://[email protected]:50088/default
        final String url = "oms:joyqueue://" + app +  "@" + brokerAddr + "/" + dataCenter;

        KeyValue keyValue = OMS.newKeyValue();
        keyValue.put(OMSBuiltinKeys.ACCOUNT_KEY, token);

        MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint(url, keyValue);

        // 使用MessagingAccessPoint创建producer
        Producer producer = messagingAccessPoint.createProducer();
        producer.start();

        // 使用producer.createMessage方法创建message
        Message message = producer.createMessage(topic, "Message body".getBytes());

        // 设置messageKey,非必填
        // 如果需要相对顺序消息,也可以使用messageKey作为key指定分区
//        message.extensionHeader().get().setMessageKey("test_key");

        // 自定义发送的partition
        // 最好根据元数据自定义分配,不要写死partitions
//        List<QueueMetaData.Partition> partitions = producer.getQueueMetaData("test_topic_0").partitions();
//        QueueMetaData.Partition partition = partitions.get((int) SystemClock.now() % partitions.size());
//        message.extensionHeader().get().setPartition(partition.partitionId());

        // 生产消息,不抛异常就算成功,sendResult里的messageId暂时没有意义
        SendResult sendResult = producer.send(message);

        // 打印生产结果
        System.out.println(String.format("messageId: %s", sendResult.messageId()));
    }
 
Example #18
Source File: SpringBootMain.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    for (int i = 0; i < 10; i++) {
        Message message = producer.createMessage("test_topic_0", "test".getBytes());
        SendResult sendResult = producer.send(message);
        logger.info("sendResult: {}", sendResult);
    }
}
 
Example #19
Source File: OMSUtil.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
/**
 * Convert a RocketMQ SEND_OK SendResult instance to a OMS SendResult.
 */
public static SendResult sendResultConvert(org.apache.rocketmq.client.producer.SendResult rmqResult) {
    assert rmqResult.getSendStatus().equals(SendStatus.SEND_OK);
    return new SendResultImpl(rmqResult.getMsgId(), OMS.newKeyValue());
}
 
Example #20
Source File: SimplePullConsumer.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    final MessagingAccessPoint messagingAccessPoint =
        OMS.getMessagingAccessPoint("oms:rocketmq://localhost:9876/default:default");

    messagingAccessPoint.startup();

    final Producer producer = messagingAccessPoint.createProducer();

    final PullConsumer consumer = messagingAccessPoint.createPullConsumer(
        OMS.newKeyValue().put(OMSBuiltinKeys.CONSUMER_ID, "OMS_CONSUMER"));

    messagingAccessPoint.startup();
    System.out.printf("MessagingAccessPoint startup OK%n");

    final String queueName = "TopicTest";

    producer.startup();
    Message msg = producer.createBytesMessage(queueName, "Hello Open Messaging".getBytes());
    SendResult sendResult = producer.send(msg);
    System.out.printf("Send Message OK. MsgId: %s%n", sendResult.messageId());
    producer.shutdown();

    consumer.attachQueue(queueName);

    consumer.startup();
    System.out.printf("Consumer startup OK%n");

    // Keep running until we find the one that has just been sent
    boolean stop = false;
    while (!stop) {
        Message message = consumer.receive();
        if (message != null) {
            String msgId = message.sysHeaders().getString(Message.BuiltinKeys.MESSAGE_ID);
            System.out.printf("Received one message: %s%n", msgId);
            consumer.ack(msgId);

            if (!stop) {
                stop = msgId.equalsIgnoreCase(sendResult.messageId());
            }

        } else {
            System.out.printf("Return without any message%n");
        }
    }

    consumer.shutdown();
    messagingAccessPoint.shutdown();
}
 
Example #21
Source File: SimpleProducer.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    final MessagingAccessPoint messagingAccessPoint =
        OMS.getMessagingAccessPoint("oms:rocketmq://localhost:9876/default:default");

    final Producer producer = messagingAccessPoint.createProducer();

    messagingAccessPoint.startup();
    System.out.printf("MessagingAccessPoint startup OK%n");

    producer.startup();
    System.out.printf("Producer startup OK%n");

    {
        Message message = producer.createBytesMessage("OMS_HELLO_TOPIC", "OMS_HELLO_BODY".getBytes(Charset.forName("UTF-8")));
        SendResult sendResult = producer.send(message);
        //final Void aVoid = result.get(3000L);
        System.out.printf("Send async message OK, msgId: %s%n", sendResult.messageId());
    }

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    {
        final Future<SendResult> result = producer.sendAsync(producer.createBytesMessage("OMS_HELLO_TOPIC", "OMS_HELLO_BODY".getBytes(Charset.forName("UTF-8"))));
        result.addListener(new FutureListener<SendResult>() {
            @Override
            public void operationComplete(Future<SendResult> future) {
                if (future.getThrowable() != null) {
                    System.out.printf("Send async message Failed, error: %s%n", future.getThrowable().getMessage());
                } else {
                    System.out.printf("Send async message OK, msgId: %s%n", future.get().messageId());
                }
                countDownLatch.countDown();
            }
        });
    }

    {
        producer.sendOneway(producer.createBytesMessage("OMS_HELLO_TOPIC", "OMS_HELLO_BODY".getBytes(Charset.forName("UTF-8"))));
        System.out.printf("Send oneway message OK%n");
    }

    try {
        countDownLatch.await();
        Thread.sleep(500); // Wait some time for one-way delivery.
    } catch (InterruptedException ignore) {
    }

    producer.shutdown();
}
 
Example #22
Source File: ProducerImpl.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Override
public SendResult send(final Message message) {
    return send(message, this.rocketmqProducer.getSendMsgTimeout());
}
 
Example #23
Source File: ProducerWrapper.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
public Future<SendResult> sendAsync(List<Message> messages) {
    return delegate.sendAsync(messages);
}
 
Example #24
Source File: ProducerWrapper.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
public Future<SendResult> sendAsync(Message message) {
    return delegate.sendAsync(message);
}
 
Example #25
Source File: ProducerImpl.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Override
public SendResult send(final Message message, final KeyValue properties) {
    long timeout = properties.containsKey(Message.BuiltinKeys.TIMEOUT)
        ? properties.getInt(Message.BuiltinKeys.TIMEOUT) : this.rocketmqProducer.getSendMsgTimeout();
    return send(message, timeout);
}
 
Example #26
Source File: ProducerWrapper.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
public SendResult send(Message message) {
    return delegate.send(message);
}
 
Example #27
Source File: ProducerImpl.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Override
public SendResult send(Message message, LocalTransactionExecutor branchExecutor, KeyValue attributes) {
    return null;
}
 
Example #28
Source File: ProducerImpl.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Override
public Promise<SendResult> sendAsync(final Message message) {
    return sendAsync(message, this.rocketmqProducer.getSendMsgTimeout());
}
 
Example #29
Source File: ProducerImpl.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Override
public Promise<SendResult> sendAsync(final Message message, final KeyValue properties) {
    long timeout = properties.containsKey(Message.BuiltinKeys.TIMEOUT)
        ? properties.getInt(Message.BuiltinKeys.TIMEOUT) : this.rocketmqProducer.getSendMsgTimeout();
    return sendAsync(message, timeout);
}
 
Example #30
Source File: SimplePullConsumer.java    From rocketmq-4.3.0 with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    final MessagingAccessPoint messagingAccessPoint =
        OMS.getMessagingAccessPoint("oms:rocketmq://localhost:9876/default:default");

    messagingAccessPoint.startup();

    final Producer producer = messagingAccessPoint.createProducer();

    final PullConsumer consumer = messagingAccessPoint.createPullConsumer(
        OMS.newKeyValue().put(OMSBuiltinKeys.CONSUMER_ID, "OMS_CONSUMER"));

    messagingAccessPoint.startup();
    System.out.printf("MessagingAccessPoint startup OK%n");

    final String queueName = "TopicTest";

    producer.startup();
    Message msg = producer.createBytesMessage(queueName, "Hello Open Messaging".getBytes());
    SendResult sendResult = producer.send(msg);
    System.out.printf("Send Message OK. MsgId: %s%n", sendResult.messageId());
    producer.shutdown();

    consumer.attachQueue(queueName);

    consumer.startup();
    System.out.printf("Consumer startup OK%n");

    // Keep running until we find the one that has just been sent
    boolean stop = false;
    while (!stop) {
        Message message = consumer.receive();
        if (message != null) {
            String msgId = message.sysHeaders().getString(Message.BuiltinKeys.MESSAGE_ID);
            System.out.printf("Received one message: %s%n", msgId);
            consumer.ack(msgId);

            if (!stop) {
                stop = msgId.equalsIgnoreCase(sendResult.messageId());
            }

        } else {
            System.out.printf("Return without any message%n");
        }
    }

    consumer.shutdown();
    messagingAccessPoint.shutdown();
}