我试图让我的服务从头到尾重新读取kafka主题,以初始化内部数据结构。我正在使用Confluent .NET客户端。 据我了解,以下代码应使我对主题设置偏移一开始:
consumer.Assign(new TopicPartitionOffset(topic, Partition.Any, Offset.Beginning));
但是由于某种原因,我没有收到不是主题中预先存在的消息,而是新消息。 我对Assign()方法的理解错误吗?有没有一种方法可以使用Subscribe()获得所需的结果,而无需使用kafka CLI硬重置偏移量?
这里是完整的测试客户端,尽管主题有消息且有新消息到来,但我的输出始终为“无消息...”。
static void Main(string[] args)
{
var config = new ConsumerConfig
{
BootstrapServers = "localhost:9092",
GroupId = "test-consumer",
AutoOffsetReset = AutoOffsetReset.Earliest,
};
var consumer = new ConsumerBuilder<Null, byte[]>(config).Build();
var topic = "test-topic";
consumer.Assign(new TopicPartitionOffset(topic, Partition.Any, Offset.Beginning));
while (true)
{
var result = consumer.Consume(TimeSpan.FromSeconds(5));
if (result == null)
Console.WriteLine("No messages...");
else
Console.WriteLine($"Offset: {result.Offset}");
}
}
答案 0 :(得分:0)
您为什么要使用Assign
?以下应为您工作:
public static void Main(string[] args)
{
var conf = new ConsumerConfig
{
GroupId = "test-consumer",
BootstrapServers = "localhost:9092",
AutoOffsetReset = AutoOffsetReset.Earliest
};
using (var c = new ConsumerBuilder<Ignore, string>(conf).Build())
{
c.Subscribe("test-topic");
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => {
e.Cancel = true; // prevent the process from terminating.
cts.Cancel();
};
try
{
while (true)
{
try
{
var cr = c.Consume(cts.Token);
Console.WriteLine($"Message '{cr.Value}' at: '{cr.TopicPartitionOffset}'.");
}
catch (ConsumeException e)
{
Console.WriteLine($"Error: {e.Error.Reason}");
}
}
}
catch (OperationCanceledException)
{
c.Close();
}
}
}
答案 1 :(得分:0)
问题是我用Partition.Any调用了Assign(),下面的代码起作用了:
consumer.Assign(new TopicPartitionOffset(topic, new Partition(0), Offset.Beginning));