在搭建Apache Kafka平台的时候,运行测试代码时抛出以下的错误:
ExceptiException in thread "main"
org.I0Itec.zkclient.exception.ZkTimeoutException: Unable to connect
to zookeeper server within timeout: 6000
at
org.I0Itec.zkclient.ZkClient.connect(ZkClient.java:876)
at
org.I0Itec.zkclient.ZkClient.<init>(ZkClient.java:98)
at
org.I0Itec.zkclient.ZkClient.<init>(ZkClient.java:84)
at
kafka.producer.ZKBrokerPartitionInfo.<init>(ZKBrokerPartitionInfo.scala:61)
at
kafka.producer.Producer.<init>(Producer.scala:51)
at
kafka.javaapi.producer.Producer.<init>(Producer.scala:32)
at
kafka.javaapi.producer.Producer.<init>(Producer.scala:39)
看到Timeout类型的错误,因为一般网络连接建立都非常快,不会有超时的问题,所以笔者的第一想法是Kafka或Zookeeper的配置出了问题,可是改来改去并没有发现错误。后来仔细看了一下错误提示,考虑是否真的有可能在连接Zookeeper时比较耗时间也说不定,于是将timeout值加大,经测试成功。
下面是修改后的测试代码:
import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.javaapi.producer.ProducerData;
import kafka.producer.ProducerConfig;
public class Test {
public static void
main(String[] args) {
Properties props = new Properties();
props.put("zk.connect",
"9.186.66.159:2181");
props.put("serializer.class",
"kafka.serializer.StringEncoder");
// This is added by myself for changing the
default timeout 6000.
props.put("zk.connectiontimeout.ms",
"15000");
ProducerConfig config = new
ProducerConfig(props);
Producer<String,
String> producer = new
Producer<String,
String>(config);
// The message is sent to a randomly selected
partition registered in ZK
ProducerData<String,
String> data = new
ProducerData<String, String>(
"test-topic",
"test-message");
producer.send(data);
producer.close();
}
}
加载中,请稍候......