C#连接kafka示例代码
时间: 2023-07-25 10:07:38 浏览: 210
storm之集成kafka操作示例代码.zip
以下是使用 C# 连接 Kafka 的示例代码:
```csharp
using System;
using System.Collections.Generic;
using Confluent.Kafka;
class Program
{
static void Main(string[] args)
{
var config = new ConsumerConfig
{
BootstrapServers = "localhost:9092",
GroupId = "test-consumer-group",
AutoOffsetReset = AutoOffsetReset.Earliest
};
using (var consumer = new ConsumerBuilder<Ignore, string>(config).Build())
{
consumer.Subscribe("test-topic");
try
{
while (true)
{
var consumeResult = consumer.Consume(TimeSpan.FromSeconds(1));
if (consumeResult != null)
{
Console.WriteLine($"Received message: {consumeResult.Message.Value}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
finally
{
consumer.Close();
}
}
}
}
```
注意:此示例代码使用 Confluent.Kafka NuGet 包。在使用前需要先安装该包。同时,需要根据实际情况修改 Kafka 集群地址、消费者组 ID、消费主题等配置参数。
阅读全文