Java Code Examples for org.apache.rocketmq.client.consumer.DefaultMQPushConsumer#registerMessageListener()
The following examples show how to use
org.apache.rocketmq.client.consumer.DefaultMQPushConsumer#registerMessageListener() .
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: TracePushConsumer.java From rocketmq with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException, MQClientException { // Here,we use the default message track trace topic name DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("CID_JODIE_1",true); consumer.subscribe("TopicTest", "*"); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); // Wrong time format 2017_0422_221800 consumer.setConsumeTimestamp("20181109221800"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.printf("Consumer Started.%n"); }
Example 2
Source File: PushConsumer.java From rocketmq with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException, MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("CID_JODIE_1"); consumer.subscribe("TopicTest", "*"); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); //wrong time format 2017_0422_221800 consumer.setConsumeTimestamp("20181109221800"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.printf("Consumer Started.%n"); }
Example 3
Source File: PushConsumer.java From DDMQ with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException, MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("CID_JODIE_1"); consumer.subscribe("Jodie_topic_1023", "*"); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); //wrong time format 2017_0422_221800 consumer.setConsumeTimestamp("20170422221800"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.printf("Consumer Started.%n"); }
Example 4
Source File: Consumer.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException, MQClientException, IOException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("ConsumerGroupNamecc4"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File classFile = new File(classLoader.getResource("MessageFilterImpl.java").getFile()); String filterCode = MixAll.file2String(classFile); consumer.subscribe("TopicTest", "org.apache.rocketmq.example.filter.MessageFilterImpl", filterCode); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { System.out.printf(Thread.currentThread().getName() + " Receive New Messages: " + msgs + "%n"); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.printf("Consumer Started.%n"); }
Example 5
Source File: DelayConsumer.java From blog with MIT License | 6 votes |
public static void main(String[] args) throws MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("Delay_Consumer"); consumer.setNamesrvAddr("127.0.0.1:9876"); consumer.subscribe("DelayMessageTopic", "*"); consumer.registerMessageListener( new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage( List<MessageExt> msgs, ConsumeConcurrentlyContext context) { MessageExt msg = msgs.get(0); System.out.println( new String(msg.getBody()) + " storeTimestamp = " + (System.currentTimeMillis() - msg.getStoreTimestamp())); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.println("Consumer 已启动"); }
Example 6
Source File: PushConsumer.java From rocketmq-read with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException, MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_1"); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); consumer.setMessageModel(MessageModel.BROADCASTING); consumer.subscribe("TopicTest", "TagA || TagC || TagD"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.printf("Broadcast Consumer Started.%n"); }
Example 7
Source File: AliyunMqConfiguration.java From paascloud-master with Apache License 2.0 | 5 votes |
/** * Default mq push consumer default mq push consumer. * * @return the default mq push consumer * * @throws MQClientException the mq client exception */ @Bean public DefaultMQPushConsumer defaultMQPushConsumer() throws MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(paascloudProperties.getAliyun().getRocketMq().getConsumerGroup()); consumer.setNamesrvAddr(paascloudProperties.getAliyun().getRocketMq().getNamesrvAddr()); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); String[] strArray = AliyunMqTopicConstants.ConsumerTopics.UAC.split(GlobalConstant.Symbol.COMMA); for (String aStrArray : strArray) { String[] topicArray = aStrArray.split(GlobalConstant.Symbol.AT); String topic = topicArray[0]; String tags = topicArray[1]; if (PublicUtil.isEmpty(tags)) { tags = "*"; } consumer.subscribe(topic, tags); log.info("RocketMq UacPushConsumer topic = {}, tags={}", topic, tags); } consumer.registerMessageListener(uacPushMessageListener); consumer.setConsumeThreadMax(2); consumer.setConsumeThreadMin(2); taskExecutor.execute(() -> { try { Thread.sleep(5000); consumer.start(); log.info("RocketMq UacPushConsumer OK."); } catch (InterruptedException | MQClientException e) { log.error("RocketMq OpcPushConsumer, 出现异常={}", e.getMessage(), e); } }); return consumer; }
Example 8
Source File: BroadcastConsumer2.java From blog with MIT License | 5 votes |
public static void main(String[] args) throws MQClientException { /** TODO: 创建消息消费者对象 */ DefaultMQPushConsumer broadcast_consumer = new DefaultMQPushConsumer("Broadcast_Consumer"); /** TODO: 连接 namerserver */ broadcast_consumer.setNamesrvAddr("127.0.0.1:9876"); /** * TODO: 设置 Consumer 类型 * * <p>默认 CLUSTERING(集群模式,一个 Consumer Group 中的 Consumer 实例平均分摊消费消息); * * <p>BROADCASTING(广播模式,一个消息被多个 Consumer 消费) */ broadcast_consumer.setMessageModel(MessageModel.BROADCASTING); /** TODO: 订阅消息主题, 第二个参数表示 指定 订阅的 tag,* 表示全部 */ broadcast_consumer.subscribe("MyTopic", "*"); /** TODO: 注册消息监听 */ broadcast_consumer.registerMessageListener( new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage( List<MessageExt> msgs, ConsumeConcurrentlyContext context) { // TODO: 输出获取的消息 msgs.forEach(o -> System.out.println(new String(o.getBody()))); // TODO: 返回消费结果 return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); /** TODO: 启动 namerserver 连接 */ broadcast_consumer.start(); System.out.println("BroadcastConsumer2 已启动==========="); }
Example 9
Source File: RocketEventChannel.java From jstarcraft-core with Apache License 2.0 | 5 votes |
@Override public void registerMonitor(Set<Class> types, EventMonitor monitor) { try { for (Class type : types) { EventManager manager = managers.get(type); if (manager == null) { manager = new EventManager(); managers.put(type, manager); // TODO 需要防止路径冲突 String address = name + StringUtility.DOT + type.getName(); address = address.replace(StringUtility.DOT, StringUtility.DASH); DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(address); consumer.setInstanceName(name); consumer.setNamesrvAddr(connections); consumer.setConsumeMessageBatchMaxSize(1000); consumer.subscribe(address, "*"); switch (mode) { case QUEUE: { consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); consumer.setMessageModel(MessageModel.CLUSTERING); break; } case TOPIC: { consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); consumer.setMessageModel(MessageModel.BROADCASTING); break; } } EventHandler handler = new EventHandler(type, manager); consumer.registerMessageListener(handler); consumer.start(); consumers.put(type, consumer); } manager.attachMonitor(monitor); } } catch (Exception exception) { throw new RuntimeException(exception); } }
Example 10
Source File: RockMqTestCase.java From jstarcraft-core with Apache License 2.0 | 5 votes |
@Test public void testTopic() throws Exception { int size = 5; DefaultMQPushConsumer[] consumers = new DefaultMQPushConsumer[size]; for (int index = 0; index < size; index++) { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("topic"); consumer.setInstanceName("topicConsumer" + index); consumer.setNamesrvAddr("localhost:9876"); consumer.setMessageModel(MessageModel.BROADCASTING); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); consumer.setConsumeMessageBatchMaxSize(1000); consumer.subscribe("topic-message", "*"); consumer.registerMessageListener(listener); consumer.start(); consumers[index] = consumer; } DefaultMQProducer producer = new DefaultMQProducer("topic"); producer.setNamesrvAddr("localhost:9876"); producer.start(); for (int index = 0; index < 10; index++) { Message message = new Message("topic-message", "tag", ("RocketMQ 广播模式 " + index).getBytes(StringUtility.CHARSET)); producer.send(message); } semaphore.acquire(50); producer.shutdown(); for (int index = 0; index < size; index++) { consumers[index].shutdown(); } }
Example 11
Source File: SecKillChargeOrderConsumer.java From seckill-rocketmq with Apache License 2.0 | 5 votes |
@PostConstruct public void init() { defaultMQPushConsumer = new DefaultMQPushConsumer( MessageProtocolConst.SECKILL_CHARGE_ORDER_TOPIC.getConsumerGroup(), new AclClientRPCHook(new SessionCredentials(aclAccessKey, aclAccessSecret)), // 平均分配队列算法,hash new AllocateMessageQueueAveragely()); defaultMQPushConsumer.setNamesrvAddr(namesrvConfig.nameSrvAddr()); // 从头开始消费 defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); // 消费模式:集群模式 // 集群:同一条消息 只会被一个消费者节点消费到 // 广播:同一条消息 每个消费者都会消费到 defaultMQPushConsumer.setMessageModel(MessageModel.CLUSTERING); // 注册监听器 defaultMQPushConsumer.registerMessageListener(messageListener); // 设置每次拉取的消息量,默认为1 defaultMQPushConsumer.setConsumeMessageBatchMaxSize(1); // 订阅所有消息 try { defaultMQPushConsumer.subscribe(MessageProtocolConst.SECKILL_CHARGE_ORDER_TOPIC.getTopic(), "*"); // 启动消费者 defaultMQPushConsumer.start(); } catch (MQClientException e) { LOGGER.error("[秒杀下单消费者]--SecKillChargeOrderConsumer加载异常!e={}", LogExceptionWapper.getStackTrace(e)); throw new RuntimeException("[秒杀下单消费者]--SecKillChargeOrderConsumer加载异常!", e); } LOGGER.info("[秒杀下单消费者]--SecKillChargeOrderConsumer加载完成!"); }
Example 12
Source File: Consumer.java From DDMQ with Apache License 2.0 | 5 votes |
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.printf("Consumer Started.%n"); } }
Example 13
Source File: PushConsumerWithNamespace.java From rocketmq with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("InstanceTest", "cidTest"); defaultMQPushConsumer.setNamesrvAddr("127.0.0.1:9876"); defaultMQPushConsumer.subscribe("topicTest", "*"); defaultMQPushConsumer.registerMessageListener((MessageListenerConcurrently)(msgs, context) -> { msgs.stream().forEach((msg) -> { System.out.printf("Msg topic is:%s, MsgId is:%s, reconsumeTimes is:%s%n", msg.getTopic() , msg.getMsgId(), msg.getReconsumeTimes()); }); return ConsumeConcurrentlyStatus.RECONSUME_LATER; }); defaultMQPushConsumer.start(); }
Example 14
Source File: RocketMQConfig.java From SpringMVC-Project with MIT License | 5 votes |
@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 15
Source File: Consumer3.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws InterruptedException, MQClientException { /* * Instantiate with specified consumer group name. */ /** * Consumer Group,非常重要的概念,后续会慢慢补充 */ DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_4"); //指定NameServer地址,多个地址以 ; 隔开 consumer.setNamesrvAddr("127.0.0.1:9876"); /* * Specify name server addresses. * <p/> * * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR * <pre> * {@code * consumer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876"); * } * </pre> */ /* * Specify where to start in case the specified consumer group is a brand new one. */ /** * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费 * 如果非第一次启动,那么按照上次消费的位置继续消费 */ consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); /* * Subscribe one more more topics to consume. */ consumer.subscribe("TopicTest", "*"); /* * Register callback to execute on arrival of messages fetched from brokers. */ consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { try { MessageExt msg = msgs.get(0); //去掉消息返回状态看看结果 所以记住返回消息结果很重要 String msgbody = new String(msg.getBody(), "utf-8"); System.out.println(msgbody + " Receive New Messages: " + msgs); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } }); /* * Launch the consumer instance. */ consumer.start(); System.out.printf("Consumer Started.%n"); }
Example 16
Source File: Consumer1.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws InterruptedException, MQClientException { /* * Instantiate with specified consumer group name. */ /** * Consumer Group,非常重要的概念,后续会慢慢补充 */ DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_4"); //指定NameServer地址,多个地址以 ; 隔开 consumer.setNamesrvAddr("127.0.0.1:9876"); /* * Specify name server addresses. * <p/> * * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR * <pre> * {@code * consumer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876"); * } * </pre> */ /* * Specify where to start in case the specified consumer group is a brand new one. */ /** * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费 * 如果非第一次启动,那么按照上次消费的位置继续消费 */ consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); /* * Subscribe one more more topics to consume. */ consumer.subscribe("TopicTest", "*"); /* * Register callback to execute on arrival of messages fetched from brokers. */ consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { try { MessageExt msg = msgs.get(0); //通过把时间打印出来看看重试的时间效果 重试应该时间10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String msgbody = new String(msg.getBody(), "utf-8"); System.out.println(simpleDateFormat.format(new Date())+msgbody + " Receive New Messages: " + msgs); // int i=1/0; //模拟异常情况,观察消息重试情况 观察该字段的值的变化reconsumeTimes } catch (Exception e) { e.printStackTrace(); return ConsumeConcurrentlyStatus.RECONSUME_LATER; } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); /* * Launch the consumer instance. */ consumer.start(); System.out.printf("Consumer Started.%n"); }
Example 17
Source File: Consumer.java From code with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("test_quick_ms_consumer_name"); //consumer.setNamesrvAddr(Const.NAMESRV_ADDR_MASTER_SLAVE); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); consumer.subscribe("test_quick_topic", "*"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { MessageExt me = msgs.get(0); try { String topic = me.getTopic(); String tags = me.getTags(); String keys = me.getKeys(); // 模拟消息消费失败异常 //if(keys.equals("key1")) { // System.err.println("消息消费失败.."); // int a = 1/0; //} String msgBody = new String(me.getBody(), RemotingHelper.DEFAULT_CHARSET); System.err.println("topic: " + topic + ",tags: " + tags + ", keys: " + keys + ",body: " + msgBody); } catch (Exception e) { e.printStackTrace(); // 消息重发次数 int recousumeTimes = me.getReconsumeTimes(); System.err.println("recousumeTimes: " + recousumeTimes); if(recousumeTimes == 3) { /* * 对于broke消息重发到一定次数的时候 * 记录日志.... * 做补偿处理 */ System.out.println("消息无法消费 msid="+me.getMsgId()); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } // broke消息重发 return ConsumeConcurrentlyStatus.RECONSUME_LATER; } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.err.println("consumer start..."); }
Example 18
Source File: Consumer.java From code with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("test_quick_consumer_name"); consumer.setNamesrvAddr(Const.NAMESRV_ADDR_SINGLE); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); consumer.subscribe("test_quick_topic", "*"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { MessageExt me = msgs.get(0); try { String topic = me.getTopic(); String tags = me.getTags(); String keys = me.getKeys(); // 模拟消息消费失败异常 if(keys.equals("key1")) { System.err.println("消息消费失败.."); int a = 1/0; } String msgBody = new String(me.getBody(), RemotingHelper.DEFAULT_CHARSET); System.err.println("topic: " + topic + ",tags: " + tags + ", keys: " + keys + ",body: " + msgBody); } catch (Exception e) { e.printStackTrace(); // 消息重发次数 int recousumeTimes = me.getReconsumeTimes(); System.err.println("recousumeTimes: " + recousumeTimes); if(recousumeTimes == 3) { /* * 对于broke消息重发到一定次数的时候 * 记录日志.... * 做补偿处理 */ System.out.println("消息无法消费 msid="+me.getMsgId()); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } // broke消息重发 return ConsumeConcurrentlyStatus.RECONSUME_LATER; } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.err.println("consumer start..."); }
Example 19
Source File: Consumer2.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws InterruptedException, MQClientException { /* * Instantiate with specified consumer group name. */ /** * Consumer Group,非常重要的概念,后续会慢慢补充 */ DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_4"); //指定NameServer地址,多个地址以 ; 隔开 consumer.setNamesrvAddr("127.0.0.1:9876"); /* * Specify name server addresses. * <p/> * * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR * <pre> * {@code * consumer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876"); * } * </pre> */ /* * Specify where to start in case the specified consumer group is a brand new one. */ /** * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费 * 如果非第一次启动,那么按照上次消费的位置继续消费 */ consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); /* * Subscribe one more more topics to consume. */ consumer.subscribe("TopicTest", "*"); /* * Register callback to execute on arrival of messages fetched from brokers. */ consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { try { MessageExt msg = msgs.get(0); //通过把时间打印出来看看重试的时间效果 重试应该时间10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String msgbody = new String(msg.getBody(), "utf-8"); System.out.println(simpleDateFormat.format(new Date())+msgbody + " Receive New Messages: " + msgs); Thread.sleep(200000); //不模拟异常,模拟非常耗时看看效果如何??,观察消息重试情况 观察该字段的值的变化reconsumeTimes } catch (Exception e) { e.printStackTrace(); return ConsumeConcurrentlyStatus.RECONSUME_LATER; } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); /* * Launch the consumer instance. */ consumer.start(); System.out.printf("Consumer Started.%n"); }
Example 20
Source File: RocketmqConsumer.java From myth with Apache License 2.0 | 4 votes |
/** * Push consumer default mq push consumer. * * @return the default mq push consumer * @throws MQClientException the mq client exception */ @Bean public DefaultMQPushConsumer pushConsumer() throws MQClientException { /** * 一个应用创建一个Consumer,由应用来维护此对象,可以设置为全局对象或者单例<br> * 注意:ConsumerGroupName需要由应用来保证唯一 */ DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(env.getProperty("spring.rocketmq.consumerGroupName")); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); consumer.setNamesrvAddr(env.getProperty("spring.rocketmq.namesrvAddr")); consumer.setInstanceName(env.getProperty("spring.rocketmq.instanceName")); //设置批量消费,以提升消费吞吐量,默认是1 consumer.setConsumeMessageBatchMaxSize(1); /** * 订阅指定topic下tags */ consumer.subscribe(TOPIC, TOPIC); consumer.registerMessageListener((List<MessageExt> msgList, ConsumeConcurrentlyContext context) -> { MessageExt msg = msgList.get(0); try { // 默认msgList里只有一条消息,可以通过设置consumeMessageBatchMaxSize参数来批量接收消息 final byte[] message = msg.getBody(); LogUtil.debug(LOGGER, () -> "springcloud account-service rocketmq 接收到myth框架发出的信息===="); final Boolean success = mythMqReceiveService.processMessage(message); if (success) { return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } } catch (Exception e) { e.printStackTrace(); //重复消费 return ConsumeConcurrentlyStatus.RECONSUME_LATER; } //如果没有return success,consumer会重复消费此信息,直到success。 return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; }); /** * Consumer对象在使用之前必须要调用start初始化,初始化一次即可<br> */ consumer.start(); return consumer; }