似乎Kafka(https://github.com/confluentinc/confluent-kafka-dotnet)最受欢迎的.net客户端缺少设置和创建主题的方法。调用Producer.ProduceAsync()
时,主题会自动创建,但我找不到设置分区,保留策略和其他设置的方法。
我试图在网上找到任何例子,但我发现只是使用默认值。
也许还有另一个我可以使用的.net客户端吗?
Confluent.Kafka.AdminClient
可在1.0.0-experimental-2
版本中使用,但不允许创建主题等。
它建立在librdkafka
which doesn't have APIs for this yet。
所以现在你必须使用例如在代理上配置它。 bin\windows\kafka-topics.sh --create ...
汇总但没有提供任何API来从dot net客户端创建主题,但是有相同的解决方法。
- 在kafka配置中设置
auto.create.topics.enable = true
- 使用
var brokerMetadata = producer.GetMetadata(false, topicName);
查询现有代理中的可用主题,如果指定的主题不可用,则kafka将创建具有指定名称的主题。
private static bool CreateTopicIfNotExist(Producer producer, string topicName)
{
bool isTopicExist = producer.GetMetadata().Topics.Any(t => t.Topic == topicName);
if (!isTopicExist)
{
//Creates topic if it is not exist; Only in case of auto.create.topics.enable = true is set into kafka configuration
var topicMetadata = producer.GetMetadata(false, topicName).Topics.FirstOrDefault();
if (topicMetadata != null && (topicMetadata.Error.Code != ErrorCode.UnknownTopicOrPart || topicMetadata.Error.Code == ErrorCode.Local_UnknownTopic))
isTopicExist = true;
}
return isTopicExist;
}
因此你可以使用这个工作,我知道这是一个肮脏的解决方案,但似乎现在没有其他方法。
现在可以在最新版本的Confluent.Kafka .Net客户端库中找到它。
using (var adminClient = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = bootstrapServers }).Build())
{
try
{
await adminClient.CreateTopicsAsync(new TopicSpecification[] {
new TopicSpecification { Name = topicName, ReplicationFactor = 1, NumPartitions = 1 } });
}
catch (CreateTopicsException e)
{
Console.WriteLine($"An error occured creating topic {e.Results[0].Topic}: {e.Results[0].Error.Reason}");
}
}