最近写kafka程序突然发现消费者会产程空指针异常,百思不得其解于是就百度寻找解决方案。参考了一下链接网上的结论但是感觉还是不怎么样于是自己一步一步寻找根源
发现源码中这么一句代码
public Map<String, ConsumerRecords<K, V>> poll(long timeout) {
return null;
}
他直接返回了null指针,于是空指针异常就产生了,于是我产看这个类的文件地址
spark-examples-1.6.0-hadoop2.6.0.jar
他是spark-example中的类,并不是我导入的kafka文件夹中的lib包中的类,于是我把它删了,然后就可以了
我们也查看kafka中这个方法的实现
public ConsumerRecords<K, V> poll(long timeout) {
this.acquire();
try {
if(timeout < 0L) {
throw new IllegalArgumentException("Timeout must not be negative");
} else if(this.subscriptions.hasNoSubscriptionOrUserAssignment()) {
throw new IllegalStateException("Consumer is not subscribed to any topics or assigned any partitions");
} else {
long start = this.time.milliseconds();
long remaining = timeout;
do {
Map records = this.pollOnce(remaining);
if(!records.isEmpty()) {
if(this.fetcher.sendFetches() > 0 || this.client.hasPendingRequests()) {
this.client.pollNoWakeup();
}
ConsumerRecords elapsed1;
if(this.interceptors == null) {
elapsed1 = new ConsumerRecords(records);
return elapsed1;
}
elapsed1 = this.interceptors.onConsume(new ConsumerRecords(records));
return elapsed1;
}
long elapsed = this.time.milliseconds() - start;
remaining = timeout - elapsed;
} while(remaining > 0L);
ConsumerRecords records1 = ConsumerRecords.empty();
return records1;
}
} finally {
this.release();
}
}
可以看到这里并不是null所以是没问题的。希望我的方法对你也有用!