Java Code Examples for com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer#setInstanceName()

The following examples show how to use com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer#setInstanceName() . 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: Consumer.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, MQClientException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String subscription = commandLine.getOptionValue('s');
        final String returnFailedHalf = commandLine.getOptionValue('f');

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
        consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

        consumer.subscribe(topic, subscription);

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            AtomicLong consumeTimes = new AtomicLong(0);


            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                    ConsumeConcurrentlyContext context) {
                long currentTimes = this.consumeTimes.incrementAndGet();

                System.out.printf("%-8d %s\n", currentTimes, msgs);

                if (Boolean.parseBoolean(returnFailedHalf)) {
                    if ((currentTimes % 2) == 0) {
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();

        System.out.println("Consumer Started.");
    }
}
 
Example 2
Source File: Consumer.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, MQClientException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String subscription = commandLine.getOptionValue('s');
        final String returnFailedHalf = commandLine.getOptionValue('f');

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
        consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

        consumer.subscribe(topic, subscription);

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            AtomicLong consumeTimes = new AtomicLong(0);


            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                long currentTimes = this.consumeTimes.incrementAndGet();

                System.out.printf("%-8d %s%n", currentTimes, msgs);

                if (Boolean.parseBoolean(returnFailedHalf)) {
                    if ((currentTimes % 2) == 0) {
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();

        System.out.println("Consumer Started.");
    }
}
 
Example 3
Source File: Consumer.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, MQClientException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String subscription = commandLine.getOptionValue('s');
        final String returnFailedHalf = commandLine.getOptionValue('f');

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
        consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

        consumer.subscribe(topic, subscription);

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            AtomicLong consumeTimes = new AtomicLong(0);


            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                    ConsumeConcurrentlyContext context) {
                long currentTimes = this.consumeTimes.incrementAndGet();

                System.out.printf("%-8d %s\n", currentTimes, msgs);

                if (Boolean.parseBoolean(returnFailedHalf)) {
                    if ((currentTimes % 2) == 0) {
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();

        System.out.println("Consumer Started.");
    }
}
 
Example 4
Source File: Consumer.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws MQClientException {
    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long consumeTps =
                        (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = ((end[2] - begin[2]) / (double) (end[1] - begin[1]));
                final double averageS2CRT = ((end[3] - begin[3]) / (double) (end[1] - begin[1]));

                System.out.printf(
                    "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d\n"//
                    , consumeTps//
                    , averageB2CRT//
                    , averageS2CRT//
                    , end[4]//
                    , end[5]//
                    );
            }
        }


        @Override
        public void run() {
            try {
                this.printStats();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    DefaultMQPushConsumer consumer =
            new DefaultMQPushConsumer("benchmark_consumer_"
                    + Long.toString(System.currentTimeMillis() % 100));
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    consumer.subscribe("BenchmarkTest", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            // 1
            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            // 2
            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            // 3
            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            // 4
            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            // 5
            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Consumer Started.");
}
 
Example 5
Source File: Consumer.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MQClientException {
    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long consumeTps =
                        (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = ((end[2] - begin[2]) / (double) (end[1] - begin[1]));
                final double averageS2CRT = ((end[3] - begin[3]) / (double) (end[1] - begin[1]));

                System.out.printf(
                        "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n"//
                        , consumeTps//
                        , averageB2CRT//
                        , averageS2CRT//
                        , end[4]//
                        , end[5]//
                );
            }
        }


        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    DefaultMQPushConsumer consumer =
            new DefaultMQPushConsumer("benchmark_consumer_"
                    + Long.toString(System.currentTimeMillis() % 100));
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    consumer.subscribe("BenchmarkTest", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                        ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            // 1
            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            // 2
            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            // 3
            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            // 4
            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            // 5
            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Consumer Started.");
}
 
Example 6
Source File: MqConsumer.java    From RocketMqCurrencyBoot with Apache License 2.0 4 votes vote down vote up
/**
 * 启动一个消费端    
 * @param Topic   队列名称
 * @param Tags	  标签
 * @param consumeFromWhere      从哪里开始消费
 * @param messageModel 			广播  / 聚集
 * @throws Exception    		错误消息  
 */
public String init(String Topic, String Tags, ConsumeFromWhere consumeFromWhere,
		MessageModel messageModel) throws Exception
{

	// 参数信息
	logger.info(MessageFormat
			.format("消费者 初始化!  consumerGroup={0}   namesrvAddr={1}  Topic={2}   Tags={3}  ConsumeFromWhere={4}  MessageModel={5} ",
					consumerGroup, namesrvAddr, Topic, Tags, consumeFromWhere, messageModel));

	// 一个应用创建一个Consumer,由应用来维护此对象,可以设置为全局对象或者单例<br>
	// 注意:ConsumerGroupName需要由应用来保证唯一
	defaultMQPushConsumer = new DefaultMQPushConsumer(consumerGroup);
	defaultMQPushConsumer.setNamesrvAddr(namesrvAddr);
	defaultMQPushConsumer.setInstanceName(String.valueOf(System.currentTimeMillis()));

	// 订阅指定MyTopic下tags等于MyTag
	if (StringUtils.isEmpty(Topic)) throw new Exception("Topic 不能为空");
	if (StringUtils.isEmpty(Tags)) { throw new Exception("Tags 不能为空"); }

	defaultMQPushConsumer.subscribe(Topic, Tags);

	// 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
	// 如果非第一次启动,那么按照上次消费的位置继续消费
	if (consumeFromWhere == null)
	{
		consumeFromWhere = consumeFromWhere.CONSUME_FROM_FIRST_OFFSET;
	}
	defaultMQPushConsumer.setConsumeFromWhere(consumeFromWhere);

	if (messageModel == null)
	{
		messageModel = messageModel.CLUSTERING;
	}

	// 设置为集群消费(区别于广播消费)
	defaultMQPushConsumer.setMessageModel(messageModel);
	defaultMQPushConsumer.registerMessageListener(defaultMessageListener);

	// Consumer对象在使用之前必须要调用start初始化,初始化一次即可<br>
	defaultMQPushConsumer.start();

	String clientID = defaultMQPushConsumer.getClientIP() + "@"
			+ defaultMQPushConsumer.getInstanceName();

	logger.info("消费者 " + clientID + "启动成功!");

	return clientID;
}
 
Example 7
Source File: Consumer.java    From RocketMQ-Master-analyze with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MQClientException {
    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long consumeTps =
                        (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = ((end[2] - begin[2]) / (double) (end[1] - begin[1]));
                final double averageS2CRT = ((end[3] - begin[3]) / (double) (end[1] - begin[1]));

                System.out.printf(
                    "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d\n"//
                    , consumeTps//
                    , averageB2CRT//
                    , averageS2CRT//
                    , end[4]//
                    , end[5]//
                );
            }
        }


        @Override
        public void run() {
            try {
                this.printStats();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(
        "benchmark_consumer_" + Long.toString(System.currentTimeMillis() % 100));
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    consumer.subscribe("BenchmarkTest", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            // 1
            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            // 2
            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            // 3
            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            // 4
            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            // 5
            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Consumer Started.");
}