[英]How to check whether Kafka Server is running?
我想在开始生产和消费作业之前确保 kafka 服务器是否正在运行。 它在windows环境中,这是我在eclipse中的kafka服务器代码......
Properties properties = new Properties();
properties.setProperty("broker.id", "1");
properties.setProperty("port", "9092");
properties.setProperty("log.dirs", "D://workspace//");
properties.setProperty("zookeeper.connect", "localhost:2181");
Option<String> option = Option.empty();
KafkaConfig config = new KafkaConfig(properties);
KafkaServer kafka = new KafkaServer(config, new CurrentTime(), option);
kafka.startup();
在这种情况下if (kafka != null)
是不够的,因为它总是正确的。 那么有什么方法可以知道我的 kafka 服务器正在运行并准备好供生产者使用。 我有必要检查一下,因为它会导致一些起始数据包丢失。
必须为所有 Kafka 经纪人分配一个broker.id
。 启动时,代理将在 Zookeeper 中创建一个临时节点,路径为/broker/ids/$id
。 由于节点是短暂的,一旦代理断开连接,例如通过关闭,它将被删除。
您可以像这样查看临时代理节点的列表:
echo dump | nc localhost 2181 | grep brokers
ZooKeeper 客户端接口公开了许多命令; dump
列出集群的所有会话和临时节点。
请注意,以上假设:
localhost
上的默认端口 ( 2181
) 上运行 ZooKeeper,并且该localhost
是集群的领导者zookeeper.connect
Kafka 配置没有为您的 Kafka 集群指定 chroot 环境,即它只是host:port
而不是host:port/path
我使用了AdminClient api。
Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("connections.max.idle.ms", 10000);
properties.put("request.timeout.ms", 5000);
try (AdminClient client = KafkaAdminClient.create(properties))
{
ListTopicsResult topics = client.listTopics();
Set<String> names = topics.names().get();
if (names.isEmpty())
{
// case: if no topic found.
}
return true;
}
catch (InterruptedException | ExecutionException e)
{
// Kafka is not available
}
您可以在您的机器上安装Kafkacat工具
例如在 Ubuntu 你可以使用安装它
apt-get install kafkacat
安装kafkacat后,您可以使用以下命令连接它
kafkacat -b <your-ip-address>:<kafka-port> -t test-topic
运行上述命令后,如果 kafkacat 能够建立连接,则意味着 kafka 已启动并正在运行
对于 Linux,“ps aux | grep kafka”查看结果中是否显示了 kafka 属性。 例如 /path/to/kafka/server.properties
保罗的回答非常好,从经纪人的角度来看,这实际上是 Kafka 和 Zk 如何协同工作。
我想说另一个检查 Kafka 服务器是否正在运行的简单选项是创建一个简单的 KafkaConsumer 指向集群并尝试一些操作,例如listTopics() 。 如果 kafka 服务器没有运行,你会得到一个TimeoutException然后你可以使用try-catch
语句。
def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
val props = new Properties()
props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
props.put("group.id", kafkaParams.get("group.id").get.toString)
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val simpleConsumer = new KafkaConsumer[String, String](props)
simpleConsumer.listTopics()
}
好的选择是在开始生成或使用消息之前使用AdminClient如下
private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;
try (AdminClient client = AdminClient.create(properties)) {
client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
} catch (ExecutionException ex) {
LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
return;
}
首先,您需要创建AdminClient bean:
@Bean
public AdminClient adminClient(){
Map<String, Object> configs = new HashMap<>();
configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
StringUtils.arrayToCommaDelimitedString(new Object[]{"your bootstrap server address}));
return AdminClient.create(configs);
}
然后,您可以使用此脚本:
while (true) {
Map<String, ConsumerGroupDescription> groupDescriptionMap =
adminClient.describeConsumerGroups(Collections.singletonList(groupId))
.all()
.get(10, TimeUnit.SECONDS);
ConsumerGroupDescription consumerGroupDescription = groupDescriptionMap.get(groupId);
log.debug("Kafka consumer group ({}) state: {}",
groupId,
consumerGroupDescription.state());
if (consumerGroupDescription.state().equals(ConsumerGroupState.STABLE)) {
boolean isReady = true;
for (MemberDescription member : consumerGroupDescription.members()) {
if (member.assignment() == null || member.assignment().topicPartitions().isEmpty()) {
isReady = false;
}
}
if (isReady) {
break;
}
}
log.debug("Kafka consumer group ({}) is not ready. Waiting...", groupId);
TimeUnit.SECONDS.sleep(1);
}
此脚本将每秒检查消费者组的状态,直到状态为STABLE 。 因为所有消费者都分配给主题分区,所以您可以得出结论,服务器正在运行并准备就绪。
如果服务器正在运行,您可以使用以下代码检查可用的代理。
import org.I0Itec.zkclient.ZkClient;
public static boolean isBrokerRunning(){
boolean flag = false;
ZkClient zkClient = new ZkClient(endpoint.getZookeeperConnect(), 10000);//, kafka.utils.ZKStringSerializer$.MODULE$);
if(zkClient!=null){
int brokersCount = zkClient.countChildren(ZkUtils.BrokerIdsPath());
if(brokersCount > 0){
logger.info("Following Broker(s) {} is/are available on Zookeeper.",zkClient.getChildren(ZkUtils.BrokerIdsPath()));
flag = true;
}
else{
logger.error("ERROR:No Broker is available on Zookeeper.");
}
zkClient.close();
}
return flag;
}
我在融合的 Kafka 中发现了一个OnError
事件:
consumer.OnError += Consumer_OnError;
private void Consumer_OnError(object sender, Error e)
{
Debug.Log("connection error: "+ e.Reason);
ConsumerConnectionError(e);
}
以及它的代码文档:
//
// Summary:
// Raised on critical errors, e.g. connection failures or all brokers down. Note
// that the client will try to automatically recover from errors - these errors
// should be seen as informational rather than catastrophic
//
// Remarks:
// Executes on the same thread as every other Consumer event handler (except OnLog
// which may be called from an arbitrary thread).
public event EventHandler<Error> OnError;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.