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

The following examples show how to use org.apache.rocketmq.client.producer.DefaultMQProducer#start() . 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: 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 2
Source File: AsyncTraceAppender.java    From rocketmq-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * 构造消息类型的轨迹数据发送器
 *
 * @param properties 参数属性
 * @throws MQClientException 消息异常
 */
public AsyncTraceAppender(Properties properties) throws MQClientException {
    transDataList = new ArrayList<OnsTraceTransferBean>();
    traceProducer = new DefaultMQProducer();

    this.traceProducer.setProducerGroup(OnsTraceConstants.groupName);
    traceProducer.setSendMsgTimeout(5000);
    traceProducer.setInstanceName(properties.getProperty(OnsTraceConstants.InstanceName, String.valueOf(System.currentTimeMillis())));

    String nameSrv = properties.getProperty(OnsTraceConstants.NAMESRV_ADDR);
    if (nameSrv == null) {
        TopAddressing topAddressing = new TopAddressing(properties.getProperty(OnsTraceConstants.ADDRSRV_URL));
        nameSrv = topAddressing.fetchNSAddr();
    }
    traceProducer.setNamesrvAddr(nameSrv);
    traceProducer.setVipChannelEnabled(false);
    // 消息最大大小128K
    int maxSize = Integer.parseInt(properties.getProperty(OnsTraceConstants.MaxMsgSize, "128000"));
    batchSize = Integer.parseInt(properties.getProperty(OnsTraceConstants.MaxBatchNum, "1"));
    traceProducer.setMaxMessageSize(maxSize - 10 * 1000);
    traceProducer.start();
}
 
Example 3
Source File: BatchProducer.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("ExampleProducerGroup");
	producer.setNamesrvAddr(RocketConfig.HOST);
	producer.start();
	producer.setRetryTimesWhenSendAsyncFailed(0);

	String topic = "BatchTest";
	List<Message> messages = new ArrayList<>();
	messages.add(new Message(topic, "TagA", "OrderID001", "Hello world 0".getBytes()));
	messages.add(new Message(topic, "TagA", "OrderID002", "Hello world 1".getBytes()));
	messages.add(new Message(topic, "TagA", "OrderID003", "Hello world 2".getBytes()));
	// then you could split the large list into small ones:
	ListSplitter splitter = new ListSplitter(messages);

	while (splitter.hasNext()) {
		List<Message> listItem = splitter.next();
		producer.send(listItem);
	}

	// Shut down once the producer instance is not longer in use.
	producer.shutdown();
}
 
Example 4
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 5
Source File: RockctTests.java    From java-tutorial with MIT License 6 votes vote down vote up
@Test
public void produce() throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.setNamesrvAddr("192.168.10.103:9876");
    producer.setInstanceName("Producer1");
    producer.start();
    for (int i = 0; i < 1; i++)
        try {
            {
                Message msg = new Message("TopicTest",// topic
                        "TagA",// tag
                        "OrderID188",// key
                        ("Hello MetaQ").getBytes());// body
                SendResult sendResult = producer.send(msg);
                System.out.println(sendResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    producer.shutdown();

}
 
Example 6
Source File: TraceProducer.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",true);
        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 7
Source File: AsyncProducer.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args)
		throws MQClientException, RemotingException, InterruptedException, UnsupportedEncodingException {
	DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName2");
	producer.setRetryTimesWhenSendAsyncFailed(3);
	producer.setNamesrvAddr("192.168.237.128:9876");
	producer.start();
	for (int i = 0; i < 1; i++) {
		Message msg = new Message("TopicTest6", "TagA",
				("Hello RocketMQ" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
		producer.send(msg, new SendCallback() {
			@Override
			public void onSuccess(SendResult sendResult) {
				System.out.println(sendResult);
			}

			@Override
			public void onException(Throwable e) {
				e.printStackTrace();
			}
		});
	}
}
 
Example 8
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 9
Source File: Producer.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();

    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 10
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 11
Source File: RequestProducer.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    String producerGroup = "please_rename_unique_group_name";
    String topic = "RequestTopic";
    long ttl = 3000;

    DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
    producer.start();

    try {
        Message msg = new Message(topic,
            "",
            "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));

        long begin = System.currentTimeMillis();
        Message retMsg = producer.request(msg, ttl);
        long cost = System.currentTimeMillis() - begin;
        System.out.printf("request to <%s> cost: %d replyMessage: %s %n", topic, cost, retMsg);
    } catch (Exception e) {
        e.printStackTrace();
    }
    producer.shutdown();
}
 
Example 12
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 13
Source File: CanalRocketMQProducer.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
@Override
public void init(MQProperties rocketMQProperties) {
    this.mqProperties = rocketMQProperties;
    RPCHook rpcHook = null;
    if (rocketMQProperties.getAliyunAccessKey().length() > 0
        && rocketMQProperties.getAliyunSecretKey().length() > 0) {
        SessionCredentials sessionCredentials = new SessionCredentials();
        sessionCredentials.setAccessKey(rocketMQProperties.getAliyunAccessKey());
        sessionCredentials.setSecretKey(rocketMQProperties.getAliyunSecretKey());
        rpcHook = new ClientRPCHook(sessionCredentials);
    }

    defaultMQProducer = new DefaultMQProducer(rocketMQProperties.getProducerGroup(), rpcHook);
    defaultMQProducer.setNamesrvAddr(rocketMQProperties.getServers());
    defaultMQProducer.setRetryTimesWhenSendFailed(rocketMQProperties.getRetries());
    defaultMQProducer.setVipChannelEnabled(false);
    logger.info("##Start RocketMQ producer##");
    try {
        defaultMQProducer.start();
    } catch (MQClientException ex) {
        throw new CanalServerException("Start RocketMQ producer error", ex);
    }
}
 
Example 14
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 15
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 16
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 17
Source File: RocketMqAutoConfiguration.java    From spring-boot-rocketmq-starter with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnClass(DefaultMQProducer.class)
@ConditionalOnMissingBean(DefaultMQProducer.class)
public DefaultMQProducer mqProducer() {
    DefaultMQProducer producer = new DefaultMQProducer();
    producer.setProducerGroup(rocketMqProperties.getProducerGroupName());
    producer.setNamesrvAddr(rocketMqProperties.getNameServer());

    producer.setSendMsgTimeout(rocketMqProperties.getProducerSendMsgTimeout());
    producer.setRetryTimesWhenSendFailed(rocketMqProperties.getProducerRetryTimesWhenSendFailed());
    producer.setRetryTimesWhenSendAsyncFailed(rocketMqProperties.getProducerRetryTimesWhenSendAsyncFailed());
    producer.setMaxMessageSize(rocketMqProperties.getProducerMaxMessageSize());
    producer.setCompressMsgBodyOverHowmuch(rocketMqProperties.getProducerCompressMsgBodyOverHowMuch());
    producer.setRetryAnotherBrokerWhenNotStoreOK(rocketMqProperties.isProducerRetryAnotherBrokerWhenNotStoreOk());

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        LOGGER.info("producer shutdown");
        producer.shutdown();
        LOGGER.info("producer has shutdown");
    }));

    try {
        producer.start();
        LOGGER.info("rocketmq producer started, nameserver:{}, group:{}", rocketMqProperties.getNameServer(),
                rocketMqProperties.getProducerGroupName());
    } catch (MQClientException e) {
        LOGGER.error("producer start error, nameserver:{}, group:{}", rocketMqProperties.getNameServer(),
                rocketMqProperties.getProducerGroupName(), e);
    }

    return producer;
}
 
Example 18
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 19
Source File: RocketMQConfig.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws MQClientException {
    clearUserProducer = new TransactionMQProducer(clearUserGroup);
    clearUserProducer.setNamesrvAddr(nameServerAddress);
    ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000), r -> {
        Thread thread = new Thread(r);
        thread.setName("client-transaction-msg-check-thread");
        return thread;
    });
    clearUserProducer.setExecutorService(executorService);
    clearUserProducer.setTransactionListener(applicationContext.getAutowireCapableBeanFactory().getBean(ClearUserTransactionListener.class));
    clearUserProducer.start();

    clearUserConsumer = new DefaultMQPushConsumer(clearUserGroup);
    clearUserConsumer.setNamesrvAddr(nameServerAddress);
    clearUserConsumer.subscribe(clearUserTopic, "*");
    clearUserConsumer.registerMessageListener(applicationContext.getAutowireCapableBeanFactory().getBean(ClearUserMessageListener.class));
    clearUserConsumer.start();

    chatRecordProducer = new DefaultMQProducer(chatRecordGroup);
    chatRecordProducer.setNamesrvAddr(nameServerAddress);
    chatRecordProducer.start();

    chatRecordConsumer = new DefaultMQPushConsumer(chatRecordGroup);
    chatRecordConsumer.setNamesrvAddr(nameServerAddress);
    chatRecordConsumer.subscribe(chatRecordTopic, chatRecordTags);
    chatRecordConsumer.registerMessageListener(applicationContext.getAutowireCapableBeanFactory().getBean(ChatRecordMessageListener.class));
    chatRecordConsumer.start();
}
 
Example 20
Source File: Producer.java    From rocketmq-4.3.0 with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {

        /*
         * Instantiate with a producer group name.
         */
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");

        /*
         * Specify name server addresses.
         * <p/>
         *
         * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR
         * <pre>
         * {@code
         * producer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876");
         * }
         * </pre>
         */

        /*
         * Launch the instance.
         */
        producer.start();

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

                /*
                 * 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);
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        /*
         * Shut down once the producer instance is not longer in use.
         */
        producer.shutdown();
    }