Java Code Examples for org.apache.rocketmq.client.producer.DefaultMQProducer#send()

The following examples show how to use org.apache.rocketmq.client.producer.DefaultMQProducer#send() . 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: 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 2
Source File: QueryMsgByIdSubCommand.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
private void sendMsg(final DefaultMQAdminExt defaultMQAdminExt, final DefaultMQProducer defaultMQProducer,
    final String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    try {
        MessageExt msg = defaultMQAdminExt.viewMessage(msgId);
        if (msg != null) {
            // resend msg by id
            System.out.printf("prepare resend msg. originalMsgId=%s", msgId);
            SendResult result = defaultMQProducer.send(msg);
            System.out.printf("%s", result);
        } else {
            System.out.printf("no message. msgId=%s", msgId);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: Producer.java    From rocketmq-all-4.1.0-incubating 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 4
Source File: SendMsgStatusCommand.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
    final DefaultMQProducer producer = new DefaultMQProducer("PID_SMSC", rpcHook);
    producer.setInstanceName("PID_SMSC_" + System.currentTimeMillis());

    try {
        producer.start();
        String brokerName = commandLine.getOptionValue('b').trim();
        int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128;
        int count = commandLine.hasOption('c') ? Integer.parseInt(commandLine.getOptionValue('c')) : 50;

        producer.send(buildMessage(brokerName, 16));

        for (int i = 0; i < count; i++) {
            long begin = System.currentTimeMillis();
            SendResult result = producer.send(buildMessage(brokerName, messageSize));
            System.out.printf("rt:" + (System.currentTimeMillis() - begin) + "ms, SendResult=%s", result);
        }
    } catch (Exception e) {
        throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
    } finally {
        producer.shutdown();
    }
}
 
Example 5
Source File: Producer.java    From rocketmq-4.3.0 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 < 128; 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: Producer.java    From rocketmq-all-4.1.0-incubating 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 7
Source File: TagFilterProducer.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

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

        String[] tags = new String[] {"TagA", "TagB", "TagC"};

        for (int i = 0; i < 60; i++) {
            Message msg = new Message("TagFilterTest",
                tags[i % tags.length],
                "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));

            SendResult sendResult = producer.send(msg);
            System.out.printf("%s%n", sendResult);
        }

        producer.shutdown();
    }
 
Example 8
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 9
Source File: SimpleBatchProducer.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DefaultMQProducer producer = new DefaultMQProducer("BatchProducerGroupName");
    producer.start();

    //If you just send messages of no more than 1MiB at a time, it is easy to use batch
    //Messages of the same batch should have: same topic, same waitStoreMsgOK and no schedule support
    String topic = "BatchTest";
    List<Message> messages = new ArrayList<>();
    messages.add(new Message(topic, "Tag", "OrderID001", "Hello world 0".getBytes()));
    messages.add(new Message(topic, "Tag", "OrderID002", "Hello world 1".getBytes()));
    messages.add(new Message(topic, "Tag", "OrderID003", "Hello world 2".getBytes()));

    producer.send(messages);
}
 
Example 10
Source File: AsyncSendExceptionIT.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Test(expected = org.apache.rocketmq.client.exception.MQClientException.class)
public void testSendSelectorNull() throws Exception {
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);
    MessageQueueSelector selector = null;
    producer.send(msg, selector, 100, SendCallBackFactory.getSendCallBack());
}
 
Example 11
Source File: AsyncSendExceptionIT.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueueIdBigThanQueueNum() throws Exception {
    int queueId = 100;
    sendFail = false;
    MessageQueue mq = new MessageQueue(topic, broker1Name, queueId);
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);

    producer.send(msg, mq, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
        }

        @Override
        public void onException(Throwable throwable) {
            sendFail = true;
        }
    });

    int checkNum = 50;
    while (!sendFail && checkNum > 0) {
        checkNum--;
        TestUtils.waitForMoment(100);
    }
    producer.shutdown();
    assertThat(sendFail).isEqualTo(true);
}
 
Example 12
Source File: AsyncSendExceptionIT.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Test(expected = org.apache.rocketmq.client.exception.MQClientException.class)
public void testSendSelectorNull() throws Exception {
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);
    MessageQueueSelector selector = null;
    producer.send(msg, selector, 100, SendCallBackFactory.getSendCallBack());
}
 
Example 13
Source File: AsyncProducer.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	// Instantiate with a producer group name.
	DefaultMQProducer producer = new DefaultMQProducer("ExampleProducerGroup");
	producer.setNamesrvAddr(RocketConfig.HOST);
	// 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();
			}
		});
	}
	// Shut down once the producer instance is not longer in use.
	producer.shutdown();
}
 
Example 14
Source File: Producer.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    String topic = System.getenv("TOPIC");
    if (StringUtils.isEmpty(topic)) {
        topic = "TopicTest";
    }

    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");

    producer.start();

    for (int i = 0; i < 10000000; i++)
        try {
            {
                Message msg = new Message(topic,
                    "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 15
Source File: AsyncSendExceptionIT.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueueIdSmallZero() throws Exception {
    int queueId = -100;
    sendFail = true;
    MessageQueue mq = new MessageQueue(topic, broker1Name, queueId);
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);

    producer.send(msg, mq, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            sendFail = false;
        }

        @Override
        public void onException(Throwable throwable) {
            sendFail = true;
        }
    });

    int checkNum = 50;
    while (sendFail && checkNum > 0) {
        checkNum--;
        TestUtils.waitForMoment(100);
    }
    producer.shutdown();
    assertThat(sendFail).isEqualTo(false);
}
 
Example 16
Source File: AsyncSendExceptionIT.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectorThrowsException() throws Exception {
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);
    producer.send(msg, new MessageQueueSelector() {
        @Override
        public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
            String str = null;
            return list.get(str.length());
        }
    }, null, SendCallBackFactory.getSendCallBack());
}
 
Example 17
Source File: SimpleBatchProducer.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DefaultMQProducer producer = new DefaultMQProducer("BatchProducerGroupName");
    producer.start();

    //If you just send messages of no more than 1MiB at a time, it is easy to use batch
    //Messages of the same batch should have: same topic, same waitStoreMsgOK and no schedule support
    String topic = "BatchTest";
    List<Message> messages = new ArrayList<>();
    messages.add(new Message(topic, "Tag", "OrderID001", "Hello world 0".getBytes()));
    messages.add(new Message(topic, "Tag", "OrderID002", "Hello world 1".getBytes()));
    messages.add(new Message(topic, "Tag", "OrderID003", "Hello world 2".getBytes()));

    producer.send(messages);
}
 
Example 18
Source File: Utils.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public static void checkSend(String cluster, String nameSvr, String address) throws MQClientException, NoSuchFieldException,
        SecurityException, InterruptedException, IllegalArgumentException, IllegalAccessException, UnsupportedEncodingException, MQBrokerException, RemotingException {

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

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

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

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

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

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

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

    // 报警
    if (!sendOk) {
        logger.error(String.format("[AlarmSendErr] cluster=%s, broker=%s, result=%s", cluster, address, sendResult == null ? "null" : sendResult.toString()));
    } else {
        logger.info("AlarmSendCheck cluster={}, broker={}, result={}", cluster, address, sendResult.toString());
    }
}
 
Example 19
Source File: BatchSendIT.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Test
public void testBatchSend_CheckProperties() throws Exception {
    List<Message> messageList = new ArrayList<>();
    Message message = new Message();
    message.setTopic(topic);
    message.setKeys("keys123");
    message.setTags("tags123");
    message.setWaitStoreMsgOK(false);
    message.setBuyerId("buyerid123");
    message.setFlag(123);
    message.setBody("body".getBytes());
    messageList.add(message);

    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);

    Message messageByOffset = producer.viewMessage(offsetIds[0]);
    Message messageByMsgId = producer.viewMessage(topic, msgIds[0]);

    System.out.println(messageByOffset);
    System.out.println(messageByMsgId);

    Assert.assertEquals(message.getTopic(), messageByMsgId.getTopic());
    Assert.assertEquals(message.getTopic(), messageByOffset.getTopic());

    Assert.assertEquals(message.getKeys(), messageByOffset.getKeys());
    Assert.assertEquals(message.getKeys(), messageByMsgId.getKeys());

    Assert.assertEquals(message.getTags(), messageByOffset.getTags());
    Assert.assertEquals(message.getTags(), messageByMsgId.getTags());

    Assert.assertEquals(message.isWaitStoreMsgOK(), messageByOffset.isWaitStoreMsgOK());
    Assert.assertEquals(message.isWaitStoreMsgOK(), messageByMsgId.isWaitStoreMsgOK());

    Assert.assertEquals(message.getBuyerId(), messageByOffset.getBuyerId());
    Assert.assertEquals(message.getBuyerId(), messageByMsgId.getBuyerId());

    Assert.assertEquals(message.getFlag(), messageByOffset.getFlag());
    Assert.assertEquals(message.getFlag(), messageByMsgId.getFlag());
}
 
Example 20
Source File: Utils.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public static void checkSend(String cluster, String nameSvr, String address) throws MQClientException, NoSuchFieldException,
        SecurityException, InterruptedException, IllegalArgumentException, IllegalAccessException, UnsupportedEncodingException, MQBrokerException, RemotingException {

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

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

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

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

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

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

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

    // 报警
    if (!sendOk) {
        logger.error(String.format("[AlarmSendErr] cluster=%s, broker=%s, result=%s", cluster, address, sendResult == null ? "null" : sendResult.toString()));
    } else {
        logger.info("AlarmSendCheck cluster={}, broker={}, result={}", cluster, address, sendResult.toString());
    }
}