Java Code Examples for org.apache.rocketmq.common.message.Message

The following examples show how to use org.apache.rocketmq.common.message.Message. These examples are extracted from open source projects. 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 Project: rocketmq   Source File: TestProducer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.start();

    for (int i = 0; i < 1; i++)
        try {
            {
                Message msg = new Message("TopicTest1",
                    "TagA",
                    "key113",
                    "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg);
                System.out.printf("%s%n", sendResult);

                QueryResult queryMessage =
                    producer.queryMessage("TopicTest1", "key113", 10, 0, System.currentTimeMillis());
                for (MessageExt m : queryMessage.getMessageList()) {
                    System.out.printf("%s%n", m);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    producer.shutdown();
}
 
Example 2
Source Project: DDMQ   Source File: Producer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.start();

    try {
        for (int i = 0; i < 6000000; i++) {
            Message msg = new Message("TopicFilter7",
                "TagA",
                "OrderID001",
                "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));

            msg.putUserProperty("SequenceId", String.valueOf(i));
            SendResult sendResult = producer.send(msg);
            System.out.printf("%s%n", sendResult);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    producer.shutdown();
}
 
Example 3
Source Project: rocketmq-all-4.1.0-incubating   Source File: BatchSendIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchSend_ViewMessage() throws Exception {
    List<Message> messageList = new ArrayList<>();
    int batchNum = 100;
    for (int i = 0; i < batchNum; i++) {
        messageList.add(new Message(topic, RandomUtils.getStringByUUID().getBytes()));
    }

    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);
    SendResult sendResult = producer.send(messageList);
    Assert.assertEquals(SendStatus.SEND_OK, sendResult.getSendStatus());

    String[] offsetIds = sendResult.getOffsetMsgId().split(",");
    String[] msgIds = sendResult.getMsgId().split(",");
    Assert.assertEquals(messageList.size(), offsetIds.length);
    Assert.assertEquals(messageList.size(), msgIds.length);

    Thread.sleep(2000);

    for (int i = 0; i < 3; i++) {
        producer.viewMessage(offsetIds[random.nextInt(batchNum)]);
    }
    for (int i = 0; i < 3; i++) {
        producer.viewMessage(topic, msgIds[random.nextInt(batchNum)]);
    }
}
 
Example 4
Source Project: rocketmq   Source File: Producer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {

        DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");

        producer.start();

        for (int i = 0; i < 10000000; i++)
            try {
                {
                    Message msg = new Message("TopicTest",
                        "TagA",
                        "OrderID188",
                        "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                    SendResult sendResult = producer.send(msg);
                    System.out.printf("%s%n", sendResult);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        producer.shutdown();
    }
 
Example 5
Source Project: DDMQ   Source File: TestProducer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.start();

    for (int i = 0; i < 1; i++)
        try {
            {
                Message msg = new Message("TopicTest1",
                    "TagA",
                    "key113",
                    "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg);
                System.out.printf("%s%n", sendResult);

                QueryResult queryMessage =
                    producer.queryMessage("TopicTest1", "key113", 10, 0, System.currentTimeMillis());
                for (MessageExt m : queryMessage.getMessageList()) {
                    System.out.printf("%s%n", m);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    producer.shutdown();
}
 
Example 6
public static void main(String[] args) throws Exception {
	// Instantiate with a producer group name.
	DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
	producer.setNamesrvAddr(RocketConfig.HOST);
	// Launch the instance.
	producer.start();
	for (int i = 0; i < 100; i++) {
		// Create a message instance, specifying topic, tag and message body.
		Message msg = new Message("TopicTest" /* Topic */, "TagA" /* Tag */, ("Hello RocketMQ " + i)
			.getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
		);
		// Call send message to deliver message to one of brokers.
		SendResult sendResult = producer.send(msg);
		System.out.printf("%s%n", sendResult);
	}
	// Shut down once the producer instance is not longer in use.
	producer.shutdown();
}
 
Example 7
Source Project: canal   Source File: CanalRocketMQProducer.java    License: Apache License 2.0 6 votes vote down vote up
private void sendMessage(Message message, int partition) {
    try {
        SendResult sendResult = this.defaultMQProducer.send(message, (mqs, msg, arg) -> {
            if (partition > mqs.size()) {
                return mqs.get(partition % mqs.size());
            } else {
                return mqs.get(partition);
            }
        }, null);

        if (logger.isDebugEnabled()) {
            logger.debug("Send Message Result: {}", sendResult);
        }
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source Project: rocketmq-read   Source File: SplitBatchProducer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        DefaultMQProducer producer = new DefaultMQProducer("BatchProducerGroupName");
        producer.start();

        //large batch
        String topic = "BatchTest";
        List<Message> messages = new ArrayList<>(100 * 1000);
        for (int i = 0; i < 100 * 1000; i++) {
            messages.add(new Message(topic, "Tag", "OrderID" + i, ("Hello world " + i).getBytes()));
        }

        //split the large batch into small ones:
        ListSplitter splitter = new ListSplitter(messages);
        while (splitter.hasNext()) {
            List<Message> listItem = splitter.next();
            producer.send(listItem);
        }
    }
 
Example 9
/**
 * @since version3.4.6
 */
@Test
public void testSendChinaUserProp() {
    Message msg = MessageFactory.getRandomMessage(topic);
    String msgKey = "jueyinKey";
    String msgValue = "jueyinzhi";
    msg.putUserProperty(msgKey, msgValue);

    RMQNormalConsumer consumer = getConsumer(nsAddr, topic, "*", new RMQNormalListner());

    producer.send(msg, null);
    assertThat(producer.getAllMsgBody().size()).isEqualTo(1);

    consumer.getListner().waitForMessageConsume(producer.getAllMsgBody(), consumeTime);

    Message sendMsg = (Message) producer.getFirstMsg();
    Message recvMsg = (Message) consumer.getListner().getFirstMsg();
    assertThat(recvMsg.getUserProperty(msgKey)).isEqualTo(sendMsg.getUserProperty(msgKey));
}
 
Example 10
Source Project: rocketmq   Source File: DefaultMQProducerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncRequest_OnSuccess() throws Exception {
    when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    RequestCallback requestCallback = new RequestCallback() {
        @Override public void onSuccess(Message message) {
            assertThat(message.getTopic()).isEqualTo("FooBar");
            assertThat(message.getBody()).isEqualTo(new byte[] {'a'});
            assertThat(message.getFlag()).isEqualTo(1);
            countDownLatch.countDown();
        }

        @Override public void onException(Throwable e) {
        }
    };
    producer.request(message, requestCallback, 3 * 1000L);
    ConcurrentHashMap<String, RequestResponseFuture> responseMap = RequestFutureTable.getRequestFutureTable();
    assertThat(responseMap).isNotNull();
    for (Map.Entry<String, RequestResponseFuture> entry : responseMap.entrySet()) {
        RequestResponseFuture future = entry.getValue();
        future.setSendRequestOk(true);
        message.setFlag(1);
        future.getRequestCallback().onSuccess(message);
    }
    countDownLatch.await(3000L, TimeUnit.MILLISECONDS);
}
 
Example 11
Source Project: DDMQ   Source File: MessageUserPropIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @since version3.4.6
 */
@Test
public void testSendEnglishUserProp() {
    Message msg = MessageFactory.getRandomMessage(topic);
    String msgKey = "jueyinKey";
    String msgValue = "jueyinValue";
    msg.putUserProperty(msgKey, msgValue);

    RMQNormalConsumer consumer = getConsumer(nsAddr, topic, "*", new RMQNormalListener());

    producer.send(msg, null);
    assertThat(producer.getAllMsgBody().size()).isEqualTo(1);

    consumer.getListener().waitForMessageConsume(producer.getAllMsgBody(), consumeTime);

    Message sendMsg = (Message) producer.getFirstMsg();
    Message recvMsg = (Message) consumer.getListener().getFirstMsg();
    assertThat(recvMsg.getUserProperty(msgKey)).isEqualTo(sendMsg.getUserProperty(msgKey));
}
 
Example 12
Source Project: rocketmq-4.3.0   Source File: RocketmqLogbackAppender.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Info,error,warn,callback method implementation
 */
@Override
protected void append(ILoggingEvent event) {
    if (!isStarted()) {
        return;
    }
    String logStr = this.layout.doLayout(event);
    try {
        Message msg = new Message(topic, tag, logStr.getBytes());
        msg.getProperties().put(ProducerInstance.APPENDER_TYPE, ProducerInstance.LOGBACK_APPENDER);

        //Send message and do not wait for the ack from the message broker.
        producer.sendOneway(msg);
    } catch (Exception e) {
        addError("Could not send message in RocketmqLogbackAppender [" + name + "]. Message is : " + logStr, e);
    }
}
 
Example 13
Source Project: rocketmq_trans_message   Source File: TestProducer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.start();

    for (int i = 0; i < 1; i++)
        try {
            {
                Message msg = new Message("TopicTest1",
                    "TagA",
                    "key113",
                    "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg);
                System.out.printf("%s%n", sendResult);

                QueryResult queryMessage =
                    producer.queryMessage("TopicTest1", "key113", 10, 0, System.currentTimeMillis());
                for (MessageExt m : queryMessage.getMessageList()) {
                    System.out.printf("%s%n", m);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    producer.shutdown();
}
 
Example 14
Source Project: DeFiBus   Source File: HealthyMessageQueueSelector.java    License: Apache License 2.0 6 votes vote down vote up
private MessageQueue selectMessageQueue(List<MessageQueue> mqs, AtomicInteger index, MessageQueue lastOneSelected,
    Message msg) {
    boolean isRetry = (lastOneSelected != null);
    List<MessageQueue> candidateMqs = mqs;
    if (isRetry) {
        candidateMqs = filterMqsByBrokerName(mqs, lastOneSelected.getBrokerName());
    }
    for (int i = 0; i < candidateMqs.size(); i++) {
        int pos = Math.abs(index.getAndIncrement()) % candidateMqs.size();
        MessageQueue candidate = candidateMqs.get(pos);
        if (isQueueHealthy(candidate)) {
            return candidate;
        }
    }
    return null;
}
 
Example 15
Source Project: rocketmq-4.3.0   Source File: MQMessageFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Object> getRMQMessage(String tag, String topic, int msgSize) {
    List<Object> msgs = new ArrayList<Object>();
    for (int i = 0; i < msgSize; i++) {
        msgs.add(new Message(topic, tag, RandomUtil.getStringByUUID().getBytes()));
    }

    return msgs;
}
 
Example 16
Source Project: j360-boot-app-all   Source File: MQProducter.java    License: Apache License 2.0 5 votes vote down vote up
public void createPushMessage(Message message) {
    message.setTags("PUSH");
    try {
        rocketMQProducerTemplate.send(message);
    } catch (MQBrokerException | MQClientException | RemotingException | InterruptedException e) {
        throw new ServiceException(DefaultErrorCode.SYSTEM_ERROR, e);
    }
}
 
Example 17
Source Project: DeFiBus   Source File: DeFiBusCLientUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createReplyMessage_Success() {
    MessageExt msg = new MessageExt();
    msg.setTopic("Test");
    msg.putUserProperty(DeFiBusConstant.PROPERTY_MESSAGE_CLUSTER, "ClusterName");
    msg.putUserProperty(DeFiBusConstant.PROPERTY_MESSAGE_REPLY_TO, "reply_to");
    msg.putUserProperty(DeFiBusConstant.PROPERTY_RR_REQUEST_ID, "w/request_id");
    msg.putUserProperty(DeFiBusConstant.PROPERTY_MESSAGE_BROKER, "BrokerName");

    byte[] replyContent = "reply content".getBytes();
    Message replyMsg = DeFiBusClientUtil.createReplyMessage(msg, replyContent);

    assertThat(replyMsg).isNotNull();
    assertThat(replyContent).isEqualTo(replyMsg.getBody());
}
 
Example 18
Source Project: rocketmq   Source File: TransactionProducer.java    License: Apache License 2.0 5 votes vote down vote up
private static Message buildMessage(TxSendConfig config) {
    byte[] bs = new byte[config.messageSize];
    ThreadLocalRandom r = ThreadLocalRandom.current();
    r.nextBytes(bs);

    ByteBuffer buf = ByteBuffer.wrap(bs);
    buf.putLong(config.batchId);
    long sendMachineId = START_TIME << 32;
    long msgId = sendMachineId | MSG_COUNT.getAndIncrement();
    buf.putLong(msgId);

    // save send tx result in message
    if (r.nextDouble() < config.sendRollbackRate) {
        buf.put((byte) LocalTransactionState.ROLLBACK_MESSAGE.ordinal());
    } else if (r.nextDouble() < config.sendUnknownRate) {
        buf.put((byte) LocalTransactionState.UNKNOW.ordinal());
    } else {
        buf.put((byte) LocalTransactionState.COMMIT_MESSAGE.ordinal());
    }

    // save check tx result in message
    for (int i = 0; i < MAX_CHECK_RESULT_IN_MSG; i++) {
        if (r.nextDouble() < config.checkRollbackRate) {
            buf.put((byte) LocalTransactionState.ROLLBACK_MESSAGE.ordinal());
        } else if (r.nextDouble() < config.checkUnknownRate) {
            buf.put((byte) LocalTransactionState.UNKNOW.ordinal());
        } else {
            buf.put((byte) LocalTransactionState.COMMIT_MESSAGE.ordinal());
        }
    }

    Message msg = new Message();
    msg.setTopic(config.topic);

    msg.setBody(bs);
    return msg;
}
 
Example 19
Source Project: DDMQ   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 5 votes vote down vote up
public void sendOneWay(Object msg) {
    Message metaqMsg = (Message) msg;
    try {
        producer.sendOneway(metaqMsg);
        msgBodys.addData(new String(metaqMsg.getBody()));
        originMsgs.addData(msg);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Source Project: DDMQ   Source File: Producer.java    License: Apache License 2.0 5 votes vote down vote up
private static Message buildMessage(final int messageSize, final String topic) throws UnsupportedEncodingException {
    Message msg = new Message();
    msg.setTopic(topic);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < messageSize; i += 10) {
        sb.append("hello baby");
    }

    msg.setBody(sb.toString().getBytes(RemotingHelper.DEFAULT_CHARSET));

    return msg;
}
 
Example 21
Source Project: rocketmq   Source File: MessageUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateReplyMessage_reqMsgIsNull() throws MQClientException {
    try {
        Message msg = MessageUtil.createReplyMessage(null, new byte[] {'a'});
        failBecauseExceptionWasNotThrown(MQClientException.class);
    } catch (MQClientException e) {
        assertThat(e).hasMessageContaining("create reply message fail, requestMessage cannot be null.");
    }
}
 
Example 22
/**
 * TODO 需学员实现
 * 下单并发送扣款事务消息
 * @param chargeOrderRequest
 * @param sessionId
 * @return
 */
@Override
public Result sendPaymentTransactionMsg(ChargeOrderRequest chargeOrderRequest, String sessionId) {
    // 本地下单,事务消息:扣款
    String purseId = chargeOrderRequest.getPurseId();
    String channelOrderId = chargeOrderRequest.getChannelOrderId();
    String merchantName = chargeOrderRequest.getMerchantName();
    String chargeMoney = chargeOrderRequest.getChargePrice();
    String userPhoneNo = chargeOrderRequest.getUserPhoneNum();
    // 消息协议组装 消息发送
    WalletPaymentProtocol walletPaymentProtocol = new WalletPaymentProtocol();
    walletPaymentProtocol.setPurseId(purseId)
            .setChannelOrderId(channelOrderId)
            .setMerchantName(merchantName)
            .setChargeMoney(chargeMoney)
            .setOrderId(UUID.randomUUID().toString())
            .setUserPhoneNo(userPhoneNo);
    String msgBody = walletPaymentProtocol.encode();
    try {
        // 发送扣款事务消息
        Message message = new Message(MessageProtocolConst.WALLET_PAYMENT_TOPIC.getTopic(), msgBody.getBytes());
        SendResult sendResult = chargeOrderPaymentTranProducer.getProducer().sendMessageInTransaction(message, null);
        if (sendResult == null) {
            LOGGER.error("sessionId={},扣款事务消息投递失败,msgBody={},sendResult=null", sessionId, msgBody);
            return new Result("20000", "FAIL", null);
        }
        // 订单已入库,状态修改为处理中
        OrderInfoDO orderInfoDO = new OrderInfoDO().setChannelOrderId(channelOrderId).setOrderId(walletPaymentProtocol.getOrderId());
        orderChargeService.updateOrderDealing(orderInfoDO);
        // 订单接收成功
        LOGGER.info("sessionId={},收单成功,扣款事务消息投递成功.msgBody={},sendResult={}", sessionId, msgBody, JSON.toJSONString(sendResult));
        return new Result("10000", "SUCCESS", chargeOrderRequest);
    } catch (MQClientException e) {
        // 消息发送异常,按下单失败处理
        LOGGER.error("sessionId={}, 扣款事务消息发送异常,协议体={},e={}", sessionId, msgBody, LogExceptionWapper.getStackTrace(e));
    }
    return new Result("20000", "FAIL", null);
}
 
Example 23
Source Project: rocketmq-4.3.0   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 5 votes vote down vote up
public void asyncSend(int msgSize) {
    this.msgSize = msgSize;

    for (int i = 0; i < msgSize; i++) {
        Message msg = new Message(topic, RandomUtil.getStringByUUID().getBytes());
        this.asyncSend(msg);
    }
}
 
Example 24
Source Project: rocketmq   Source File: TransactionMQProducer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method will be removed in the version 5.0.0, method <code>sendMessageInTransaction(Message,Object)</code>}
 * is recommended.
 */
@Override
@Deprecated
public TransactionSendResult sendMessageInTransaction(final Message msg,
    final LocalTransactionExecuter tranExecuter, final Object arg) throws MQClientException {
    if (null == this.transactionCheckListener) {
        throw new MQClientException("localTransactionBranchCheckListener is null", null);
    }

    msg.setTopic(NamespaceUtil.wrapNamespace(this.getNamespace(), msg.getTopic()));
    return this.defaultMQProducerImpl.sendMessageInTransaction(msg, tranExecuter, arg);
}
 
Example 25
/**
 * 异步发送消息
 * @param message msgObj
 * @param sendCallback 回调
 * @throws MQException 消息异常
 */
public void asyncSend(Message message, SendCallback sendCallback) throws MQException {
    try {
        producer.send(message, sendCallback);
        log.debug("send rocketmq message async");
    } catch (Exception e) {
        log.error("消息发送失败,topic : {}, msgObj {}", message.getTopic(), message);
        throw new MQException("消息发送失败,topic :" + message.getTopic() + ",e:" + e.getMessage());
    }
}
 
Example 26
Source Project: rocketmq-read   Source File: Producer.java    License: Apache License 2.0 5 votes vote down vote up
private static Message buildMessage(final int messageSize, final String topic) throws UnsupportedEncodingException {
    Message msg = new Message();
    msg.setTopic(topic);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < messageSize; i += 10) {
        sb.append("hello baby");
    }

    msg.setBody(sb.toString().getBytes(RemotingHelper.DEFAULT_CHARSET));

    return msg;
}
 
Example 27
Source Project: rocketmq   Source File: MQMessageFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Object> getMessageBody(List<Object> msgs) {
    List<Object> msgBodys = new ArrayList<Object>();
    for (Object msg : msgs) {
        msgBodys.add(new String(((Message) msg).getBody()));
    }

    return msgBodys;
}
 
Example 28
Source Project: rocketmq_trans_message   Source File: MQMessageFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Object> getRMQMessage(List<String> tags, String topic, int msgSize) {
    List<Object> msgs = new ArrayList<Object>();
    for (int i = 0; i < msgSize; i++) {
        for (String tag : tags) {
            msgs.add(new Message(topic, tag, RandomUtil.getStringByUUID().getBytes()));
        }
    }
    return msgs;
}
 
Example 29
Source Project: rocketmq   Source File: MQMessageFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Object> getMsg(String topic, int msgSize, String tag) {
    List<Object> msgs = new ArrayList<Object>();
    while (msgSize > 0) {
        Message msg = new Message(topic, (index++).toString().getBytes());
        if (tag != null) {
            msg.setTags(tag);
        }
        msgs.add(msg);
        msgSize--;
    }

    return msgs;
}
 
Example 30
Source Project: DDMQ   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 5 votes vote down vote up
public void asyncSend(int msgSize, MessageQueueSelector selector) {
    this.msgSize = msgSize;
    for (int i = 0; i < msgSize; i++) {
        Message msg = new Message(topic, RandomUtil.getStringByUUID().getBytes());
        this.asyncSend(msg, selector, i);
    }
}