问题描述:
使用新版kafka-clients包消费数据,程序未报任何异常,阻塞在poll,网上说是poll没数据就阻塞,但是看是有数据的,搞了半天发现是因为访问地址的问题。
出问题的配置:
kafka.point.host=10.2.1.55:6667
kafka.point.topic=galileo.metrics
解决后的配置:
kafka.point.host=v30:6667,v31:6667
kafka.point.topic=galileo.metrics
第一个问题,新版的不再连zk而是直连kafka。
第二个问题,直接配置ip不等于host访问. 配了host访问hostname就搞定了。老大说nginx对于这种ip和host处理是不一样的,可能造成了 访问不到.
最后一个问题:为什么访问不到没有报错?而是阻塞??????以后发现了 补上。
另外注意 producer新版api直连,不连zookeeper,否则报错 无法更新metadata
代码:
1.Consumer.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
/**
* kafka数据源 可以配置多个数据来源
* @author Mingchenchen
* @Date 2017-04-07
*
*/
public class KafkaSource implements PointSource{
/**
* poll时长 : 毫秒
*/
private final int pollMillions = 100;
/**
* 数据源适配器
*/
private final SourceAdaptor sourceAdaptor;
/**
* 客户端消费者
*/
private final KafkaConsumer<String, String> consumer;
/**
* 数据源名称
*/
private final String name;
/**
*
* @param commonProperties
* @param properties
* @param topics
* @param adaptor
* @param pollTimeSec
* @param name
*/
public KafkaSource(Properties commonProperties,
Properties properties,
List<String> topics,
SourceAdaptor adaptor,
String name){
Properties allProperties = commonProperties;
allProperties.putAll(properties);
consumer = new KafkaConsumer<>(allProperties);
consumer.subscribe(topics);
this.sourceAdaptor = adaptor;
this.name = name;
}
public List<String> poll(){
try {
ConsumerRecords<String, String> consumerRecords = consumer.poll(pollMillions);
List<String> records = new ArrayList<>(consumerRecords.count());
//key is null
for (ConsumerRecord<String, String> record : consumerRecords) {
records.add(record.value());
}
return records;
} catch (Exception e) {
throw new KafkaPollException(e);
}
}
public List<Map<String, String>> pollWithKey(){
try {
ConsumerRecords<String, String> consumerRecords = consumer.poll(pollMillions);
List<Map<String, String>> records = new ArrayList<>(consumerRecords.count());
//key is null
for (ConsumerRecord<String, String> record : consumerRecords) {
Map<String, String> map = new HashMap<>();
map.put("ke