kafka消费失败多次重试

Thread consumerThread = new Thread(new Runnable() {

			public void run() {
				MessageAndMetadata<byte[], byte[]> messageAndMetadata = null;
				try {
					while (consumer.hasNext() && !Thread.interrupted()) {
							messageAndMetadata = consumer.getData();
						    try {
								messageHandler.onMsg(new String(messageAndMetadata.message(), "UTF-8"));
							} catch (Exception ee) {
								long retries = messageHandler.getErrorMaxRetries();
								// range from 1 ~ DEFAULT_MAX_RETRIES do as it, other retry DEFAULT_MAX_RETRIES times
								if (retries != -1) {
									if (retries<=0 || retries>DEFAULT_MAX_RETRIES) {
										retries = DEFAULT_MAX_RETRIES;
									}
									for (int i=0; i<retries; i++) {
										LOG.info(String.format("[USING RETRY] %s times, for consuming topic:%s, sleeping %s seconds", (i+1), topic, RETRY_INTERVAL_ARR[i]));
										try {
											Thread.sleep(RETRY_INTERVAL_ARR[i]*1000);
											messageHandler.onMsg(new String(messageAndMetadata.message(), "UTF-8"));
										} catch (Exception e1) {
											LOG.error(e1.getMessage(), e1);
										}
									}
								} else {
									LOG.error(String.format("[NO RETRY] Processing msg:[%s] met error, please check it.", new String(messageAndMetadata.message(), "UTF-8")), ee);
								}
							}

							messageHandler.increment();

							// should commit offset or not
							if (messageHandler.shouldCommit()) {
								consumer.commitOffsets();
								messageHandler.setLastTimeCommit(System
										.currentTimeMillis());
								if (LOG.isInfoEnabled()) {
									LOG.info("Successfully commitOffsets, topic:"
											+ messageAndMetadata.topic()
											+" partition: "
											+messageAndMetadata.partition()
											+ " offset: "
											+ messageAndMetadata.offset());

								}
							}

						}
				} catch (Exception e) {
						try {
							if (messageAndMetadata != null) {
								LOG.error(Joiner.on("").join("topic:", messageAndMetadata.topic(),
										" partition:", messageAndMetadata.partition(),
										" msgContent:", new String(messageAndMetadata.message(), "UTF-8")), e);
							}
						} catch (UnsupportedEncodingException e1) {
							LOG.error(e1.getMessage(), e1);
						}
				} finally {
					LOG.info(String.format("DafkaConsumer thread for topic:%s will give up, try me later...", topic));
					if (consumer!=null) {
						consumer.shutdown();
					}
				}

			}
		});
		consumerThread.setName("DafkaConsumerThread-"
				+ properties.getProperty("topic"));
		consumerThread.start();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值