org.apache.rocketmq.client.producer.DefaultMQProducer Java Examples

The following examples show how to use org.apache.rocketmq.client.producer.DefaultMQProducer. 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: 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 #2
Source File: SendMsgStatusCommand.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    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=" + result);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        producer.shutdown();
    }
}
 
Example #3
Source File: QueryMsgByIdSubCommand.java    From rocketmq-all-4.1.0-incubating 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=" + msgId);
            SendResult result = defaultMQProducer.send(msg);
            System.out.printf("%s", result);
        } else {
            System.out.printf("no message. msgId=" + msgId);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #4
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 #5
Source File: SendMsgStatusCommand.java    From rocketmq 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 #6
Source File: Producer.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ruubypaytest");
    producer.setNamesrvAddr("127.0.0.1:9876");
    CountDownLatch latch = new CountDownLatch(1);
    producer.start();

    try {
        for (int i = 0; i < 6000000; i++) {

                Message msg = new Message("face-manager-1",
                        "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();
    }
    Thread.sleep(10000);
    producer.shutdown();
}
 
Example #7
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();

    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 #8
Source File: ProducerInstance.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
public MQProducer getInstance(String nameServerAddress, String group) throws MQClientException {
    if (StringUtils.isBlank(group)) {
        group = DEFAULT_GROUP;
    }

    String genKey = genKey(nameServerAddress, group);
    MQProducer p = getProducerInstance().producerMap.get(genKey);
    if (p != null) {
        return p;
    }

    DefaultMQProducer defaultMQProducer = new DefaultMQProducer(group);
    defaultMQProducer.setNamesrvAddr(nameServerAddress);
    MQProducer beforeProducer = null;
    beforeProducer = getProducerInstance().producerMap.putIfAbsent(genKey, defaultMQProducer);
    if (beforeProducer != null) {
        return beforeProducer;
    }
    defaultMQProducer.start();
    return defaultMQProducer;
}
 
Example #9
Source File: Validators.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
/**
 * Validate message
 */
public static void checkMessage(Message msg, DefaultMQProducer defaultMQProducer)
    throws MQClientException {
    if (null == msg) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message is null");
    }
    // topic
    Validators.checkTopic(msg.getTopic());

    // body
    if (null == msg.getBody()) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body is null");
    }

    if (0 == msg.getBody().length) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body length is zero");
    }

    if (defaultMQProducer != null && msg.getBody().length > defaultMQProducer.getMaxMessageSize()) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL,
            "the message body size over max value, MAX: " + defaultMQProducer.getMaxMessageSize());
    }
}
 
Example #10
Source File: RocketMQConfig.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
/**
 * 构建 producer 配置
 *
 * @param props    Properties
 * @param producer DefaultMQProducer
 */
public static void buildProducerConfigs(Properties props, DefaultMQProducer producer) {
    buildCommonConfigs(props, producer);

    String group = props.getProperty(PRODUCER_GROUP);
    if (StringUtils.isEmpty(group)) {
        group = UUID.randomUUID().toString();
    }
    producer.setProducerGroup(props.getProperty(PRODUCER_GROUP, group));

    producer.setRetryTimesWhenSendFailed(getInteger(props,
            PRODUCER_RETRY_TIMES, DEFAULT_PRODUCER_RETRY_TIMES));
    producer.setRetryTimesWhenSendAsyncFailed(getInteger(props,
            PRODUCER_RETRY_TIMES, DEFAULT_PRODUCER_RETRY_TIMES));
    producer.setSendMsgTimeout(getInteger(props,
            PRODUCER_TIMEOUT, DEFAULT_PRODUCER_TIMEOUT));
}
 
Example #11
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 #12
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 #13
Source File: RocketMQAutoConfiguration.java    From spring-boot-starter-rocketmq with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnClass(DefaultMQProducer.class)
@ConditionalOnMissingBean(DefaultMQProducer.class)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = {"name-server", "producer.group"})
public DefaultMQProducer mqProducer(RocketMQProperties rocketMQProperties) {

    RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
    String groupName = producerConfig.getGroup();
    Assert.hasText(groupName, "[spring.rocketmq.producer.group] must not be null");

    DefaultMQProducer producer = new DefaultMQProducer(producerConfig.getGroup());
    producer.setNamesrvAddr(rocketMQProperties.getNameServer());
    producer.setSendMsgTimeout(producerConfig.getSendMsgTimeout());
    producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
    producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
    producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
    producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMsgBodyOverHowmuch());
    producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryAnotherBrokerWhenNotStoreOk());

    return producer;
}
 
Example #14
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 #15
Source File: AbstractOMSProducer.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
AbstractOMSProducer(final KeyValue properties) {
    this.properties = properties;
    this.rocketmqProducer = new DefaultMQProducer();
    this.clientConfig = BeanUtils.populate(properties, ClientConfig.class);

    String accessPoints = clientConfig.getOmsAccessPoints();
    if (accessPoints == null || accessPoints.isEmpty()) {
        throw new OMSRuntimeException("-1", "OMS AccessPoints is null or empty.");
    }
    this.rocketmqProducer.setNamesrvAddr(accessPoints.replace(',', ';'));
    this.rocketmqProducer.setProducerGroup(clientConfig.getRmqProducerGroup());

    String producerId = buildInstanceName();
    this.rocketmqProducer.setSendMsgTimeout(clientConfig.getOmsOperationTimeout());
    this.rocketmqProducer.setInstanceName(producerId);
    this.rocketmqProducer.setMaxMessageSize(1024 * 1024 * 4);
    properties.put(PropertyKeys.PRODUCER_ID, producerId);
}
 
Example #16
Source File: ProducerInstance.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public MQProducer getInstance(String nameServerAddress, String group) throws MQClientException {
    if (StringUtils.isBlank(group)) {
        group = DEFAULT_GROUP;
    }

    String genKey = genKey(nameServerAddress, group);
    MQProducer p = getProducerInstance().producerMap.get(genKey);
    if (p != null) {
        return p;
    }

    DefaultMQProducer defaultMQProducer = new DefaultMQProducer(group);
    defaultMQProducer.setNamesrvAddr(nameServerAddress);
    MQProducer beforeProducer = null;
    beforeProducer = getProducerInstance().producerMap.putIfAbsent(genKey, defaultMQProducer);
    if (beforeProducer != null) {
        return beforeProducer;
    }
    defaultMQProducer.start();
    return defaultMQProducer;
}
 
Example #17
Source File: DelayProducer.java    From blog with MIT License 6 votes vote down vote up
public static void main(String[] args)
    throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
  DefaultMQProducer producer = new DefaultMQProducer("Delay_Producer");
  producer.setNamesrvAddr("127.0.0.1:9876");
  producer.start();

  String body = " Hello Delay Message " + System.currentTimeMillis();
  Message message = new Message("DelayMessageTopic", "TagA", body.getBytes());

  /**
   * TODO: 设置延迟消息 延迟等级,通过 broker 设置 delayTimeLevel
   *
   * <p>共 18 个等级: “1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h”
   */
  message.setDelayTimeLevel(3);
  SendResult result = producer.send(message);
  System.out.println(result);

  producer.shutdown();
}
 
Example #18
Source File: BatchSendIT.java    From rocketmq 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 #19
Source File: RmqClusterProducer.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
@Override
public void updateConfig() throws Exception {
    RoundRobinPickerList<DefaultMQProducer> producers = buildRMQProducerList();

    warmUp(producers);

    //swap
    RoundRobinPickerList<DefaultMQProducer> oldProducers;
    rocketMqProducerRWLock.writeLock().lock();
    oldProducers = rocketmqProducers;
    rocketmqProducers = producers;
    rocketMqProducerRWLock.writeLock().unlock();

    for (DefaultMQProducer oldProducer : oldProducers) {
        oldProducer.shutdown();
    }
}
 
Example #20
Source File: RmqClusterProducer.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
@Override
public void send(CarreraRequest request) throws Exception {
    if (canAutoBatch(request)) {
        autoBatchRmqProducer.send(request, RmqSender.RMQ_MQ_SELECTOR);
    } else {
        DefaultMQProducer producer = pickRocketMQProducer();
        if (request instanceof CarreraRequestForRMQBatch) {
            RmqSender.send(
                    producer,
                    request.toRmqMessage(),
                    request.getMessageQueue(),
                    request,
                    Constant.DEFAULT_MQ_SEND_TIMEOUT_MS
            );
        } else {
            RmqSender.send(
                    producer,
                    request,
                    request,
                    request.timeout
            );
        }
    }
}
 
Example #21
Source File: SendMsgStatusCommand.java    From DDMQ 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 #22
Source File: RocketMQAutoConfiguration.java    From rocketmq-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnClass(DefaultMQProducer.class)
@ConditionalOnMissingBean(DefaultMQProducer.class)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = {"nameServer", "producer.group"})
public DefaultMQProducer mqProducer(RocketMQProperties rocketMQProperties) {

    RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
    String groupName = producerConfig.getGroup();
    Assert.hasText(groupName, "[spring.rocketmq.producer.group] must not be null");

    DefaultMQProducer producer = new DefaultMQProducer(producerConfig.getGroup());
    producer.setNamesrvAddr(rocketMQProperties.getNameServer());
    producer.setSendMsgTimeout(producerConfig.getSendMsgTimeout());
    producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
    producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
    producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
    producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMsgBodyOverHowmuch());
    producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryAnotherBrokerWhenNotStoreOk());

    return producer;
}
 
Example #23
Source File: ProducerInstance.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
public MQProducer getInstance(String nameServerAddress, String group) throws MQClientException {
    if (StringUtils.isBlank(group)) {
        group = DEFAULT_GROUP;
    }

    String genKey = genKey(nameServerAddress, group);
    MQProducer p = getProducerInstance().producerMap.get(genKey);
    if (p != null) {
        return p;
    }

    DefaultMQProducer defaultMQProducer = new DefaultMQProducer(group);
    defaultMQProducer.setNamesrvAddr(nameServerAddress);
    MQProducer beforeProducer = null;
    beforeProducer = getProducerInstance().producerMap.putIfAbsent(genKey, defaultMQProducer);
    if (beforeProducer != null) {
        return beforeProducer;
    }
    defaultMQProducer.start();
    return defaultMQProducer;
}
 
Example #24
Source File: AbstractOMSProducer.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
AbstractOMSProducer(final KeyValue properties) {
    this.properties = properties;
    this.rocketmqProducer = new DefaultMQProducer();
    this.clientConfig = BeanUtils.populate(properties, ClientConfig.class);

    String accessPoints = clientConfig.getOmsAccessPoints();
    if (accessPoints == null || accessPoints.isEmpty()) {
        throw new OMSRuntimeException("-1", "OMS AccessPoints is null or empty.");
    }
    this.rocketmqProducer.setNamesrvAddr(accessPoints.replace(',', ';'));
    this.rocketmqProducer.setProducerGroup(clientConfig.getRmqProducerGroup());

    String producerId = buildInstanceName();
    this.rocketmqProducer.setSendMsgTimeout(clientConfig.getOmsOperationTimeout());
    this.rocketmqProducer.setInstanceName(producerId);
    this.rocketmqProducer.setMaxMessageSize(1024 * 1024 * 4);
    properties.put(PropertyKeys.PRODUCER_ID, producerId);
}
 
Example #25
Source File: ScheduledMessageProducer.java    From spring-boot-starter-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Instantiate a producer to send scheduled messages
    DefaultMQProducer producer = new DefaultMQProducer("ExampleProducerGroup");
    // Launch producer
    producer.start();
    int totalMessagesToSend = 100;
    for (int i = 0; i < totalMessagesToSend; i++) {
        Message message = new Message("TestTopic", ("Hello scheduled message " + i).getBytes());
        // This message will be delivered to consumer 10 seconds later.
        message.setDelayTimeLevel(3);
        // Send the message
        producer.send(message);
    }
   
    // Shutdown producer after use.
    producer.shutdown();
}
 
Example #26
Source File: TestProducer.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 < 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 #27
Source File: QueryMsgByIdSubCommand.java    From DDMQ 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 #28
Source File: SplitBatchProducer.java    From DDMQ 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 #29
Source File: AsyncSendExceptionIT.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Test(expected = java.lang.NullPointerException.class)
public void testSendMQNull() throws Exception {
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);
    MessageQueue messageQueue = null;
    producer.send(msg, messageQueue, SendCallBackFactory.getSendCallBack());
}
 
Example #30
Source File: ExtProducerResetConfiguration.java    From rocketmq-spring with Apache License 2.0 5 votes vote down vote up
private DefaultMQProducer createProducer(ExtRocketMQTemplateConfiguration annotation) {

        RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
        if (producerConfig == null) {
            producerConfig = new RocketMQProperties.Producer();
        }
        String nameServer = environment.resolvePlaceholders(annotation.nameServer());
        String groupName = environment.resolvePlaceholders(annotation.group());
        groupName = StringUtils.isEmpty(groupName) ? producerConfig.getGroup() : groupName;

        String ak = environment.resolvePlaceholders(annotation.accessKey());
        ak = StringUtils.isEmpty(ak) ? producerConfig.getAccessKey() : ak;
        String sk = environment.resolvePlaceholders(annotation.secretKey());
        sk = StringUtils.isEmpty(sk) ? producerConfig.getSecretKey() : sk;
        boolean isEnableMsgTrace = annotation.enableMsgTrace();
        String customizedTraceTopic = environment.resolvePlaceholders(annotation.customizedTraceTopic());
        customizedTraceTopic = StringUtils.isEmpty(customizedTraceTopic) ? producerConfig.getCustomizedTraceTopic() : customizedTraceTopic;

        DefaultMQProducer producer = RocketMQUtil.createDefaultMQProducer(groupName, ak, sk, isEnableMsgTrace, customizedTraceTopic);

        producer.setNamesrvAddr(nameServer);
        producer.setSendMsgTimeout(annotation.sendMessageTimeout() == -1 ? producerConfig.getSendMessageTimeout() : annotation.sendMessageTimeout());
        producer.setRetryTimesWhenSendFailed(annotation.retryTimesWhenSendFailed() == -1 ? producerConfig.getRetryTimesWhenSendFailed() : annotation.retryTimesWhenSendFailed());
        producer.setRetryTimesWhenSendAsyncFailed(annotation.retryTimesWhenSendAsyncFailed() == -1 ? producerConfig.getRetryTimesWhenSendAsyncFailed() : annotation.retryTimesWhenSendAsyncFailed());
        producer.setMaxMessageSize(annotation.maxMessageSize() == -1 ? producerConfig.getMaxMessageSize() : annotation.maxMessageSize());
        producer.setCompressMsgBodyOverHowmuch(annotation.compressMessageBodyThreshold() == -1 ? producerConfig.getCompressMessageBodyThreshold() : annotation.compressMessageBodyThreshold());
        producer.setRetryAnotherBrokerWhenNotStoreOK(annotation.retryNextServer());

        return producer;
    }