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

The following examples show how to use org.apache.rocketmq.common.message.Message. 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: BatchSendIT.java    From rocketmq-all-4.1.0-incubating with 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 #2
Source File: CanalRocketMQProducer.java    From canal with 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 #3
Source File: TestProducer.java    From rocketmq_trans_message with 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 #4
Source File: SplitBatchProducer.java    From rocketmq-read with 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 #5
Source File: Producer.java    From rocketmq with 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 #6
Source File: TestProducer.java    From DDMQ with 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 #7
Source File: MessageUserPropIT.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #8
Source File: SyncProducer.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
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 #9
Source File: DefaultMQProducerTest.java    From rocketmq with 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 #10
Source File: MessageUserPropIT.java    From DDMQ with 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 #11
Source File: Producer.java    From DDMQ with 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 #12
Source File: RocketmqLogbackAppender.java    From rocketmq-4.3.0 with 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 File: HealthyMessageQueueSelector.java    From DeFiBus with 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 #14
Source File: TestProducer.java    From rocketmq with 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 #15
Source File: SendMsgStatusCommand.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
private static Message buildMessage(final String topic, final int messageSize) throws UnsupportedEncodingException {
    Message msg = new Message();
    msg.setTopic(topic);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < messageSize; i += 11) {
        sb.append("hello jodie");
    }
    msg.setBody(sb.toString().getBytes(MixAll.DEFAULT_CHARSET));
    return msg;
}
 
Example #16
Source File: TransactionMQProducer.java    From rocketmq with 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 #17
Source File: DeFiBusCLientUtilTest.java    From DeFiBus with 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 File: TransactionProducer.java    From rocketmq with 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 File: RMQAsyncSendProducer.java    From DDMQ with 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 File: AbstractMQProducer.java    From rocketmq-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 异步发送消息
 * @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 #21
Source File: MQProducter.java    From j360-boot-app-all with 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 #22
Source File: Producer.java    From rocketmq-read with 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 #23
Source File: MQMessageFactory.java    From rocketmq with 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 #24
Source File: RMQAsyncSendProducer.java    From rocketmq-4.3.0 with 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 #25
Source File: MQMessageFactory.java    From rocketmq_trans_message with 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 #26
Source File: MQMessageFactory.java    From rocketmq with 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 #27
Source File: RMQAsyncSendProducer.java    From DDMQ with 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);
    }
}
 
Example #28
Source File: MQMessageFactory.java    From rocketmq-read with 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 File: MessageFactory.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
public static Collection<Message> getRandomMessageListByTag(String topic, String tags, int size) {
    List<Message> msgList = new ArrayList<Message>();
    for (int i = 0; i < size; i++) {
        msgList.add(getRandomMessageByTag(topic, tags));
    }
    return msgList;
}
 
Example #30
Source File: MQMessageFactory.java    From rocketmq with 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;
}