我在Java中有一个简单的Kafka使用者。如果Kafka经纪人不可用,我试图捕获异常。我需要它来打断线程。
我有这样的代码:
KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(kafkaConsumerProperties());
kafkaConsumer.subscribe(Arrays.asList(topic));
try {
ConsumerRecords<String, String> records = kafkaConsumer.poll(500);
// records handling
} catch(Exception e) {
System.out.println(e.getMessage());
}finally {
kafkaConsumer.close();
}
如果Kafka服务器出现故障,我不会发现任何异常,但会在日志中显示以下消息:
18/03/28 13:33:39 WARN clients.NetworkClient: [Consumer clientId=consumer-3, groupId=JAVA] Connection to node -1 could not be established. Broker may not be available.
18/03/28 13:33:40 WARN clients.NetworkClient: [Consumer clientId=consumer-1, groupId=JAVA] Connection to node -1 could not be established. Broker may not be available.
有没有办法在我的帖子中处理它?</ p>
答案 0 :(得分:0)
这样的事情可以起作用:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Starting exit...");
consumer.wakeup(); 1
try {
mainThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
您执行consumer.wakeup()
来中断当前消费者的操作。
mainThread.join()
放在那里以确保主线程实际完成并且在唤醒后的处理过程中没有关闭。请记住,shutdownHook也负责处理中断,而不仅仅是普通的程序关闭。
答案 1 :(得分:0)
我已经解决了这个问题有点笨拙,但它对我有用。
public boolean testSocket(String serversList) {
String[] sockets = serversList.split(",");
int unactive = 0;
for (int i = 0; i < sockets.length; i++) {
try {
String[] socket = sockets[i].split(":");
(new Socket(socket[0], Integer.valueOf(socket[1]))).close();
} catch (IOException e) {
unactive++;
}
}
if (unactive < sockets.length) return true;
return false;
}