using System;
using Confluent.Kafka;
class Program
{
public static async Task Main(string[] args)
{
var config = new ProducerConfig { BootstrapServers = "localhost:9092" };
using var producer = new ProducerBuilder<Null, string>(config).Build();
try
{
var result = await producer.ProduceAsync("test-topic", new Message<Null, string> { Value = "Hello Kafka!" });
Console.WriteLine($"Message sent to partition {result.Partition} with offset {result.Offset}");
}
catch (ProduceException<Null, string> e)
{
Console.WriteLine($"Error producing message: {e.Error.Reason}");
}
}
}
接下来是用C#编写的Kafka消费者示例,它从最新的数据开始读取:
csharp
using System;
using System.Threading;
using Confluent.Kafka;
class Program
{
public static void Main()
{
var conf = new ConsumerConfig
{
GroupId = "test-consumer-group",
BootstrapServers = "localhost:9092",
// 指定从最新的数据开始读取
AutoOffsetReset = AutoOffsetReset.Latest
};
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($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'.");
}
catch (ConsumeException e)
{
Console.WriteLine($"Error occured: {e.Error.Reason}");
}
}
}
catch (OperationCanceledException)
{
// 执行取消操作时将触发
c.Close();
}
}
}