我最近开始使用.NET核心开发Kafka流应用程序。我已经按照教程进行了学习:https://medium.com/@srigumm/building-realtime-streaming-applications-using-net-core-and-kafka-ad45ed081b31。
我构建了一个基本的生产者-消费者应用程序,其中生产者获取输入数据并将其推送到kafka主题中。消费者可以订阅主题并消费其中的数据。我还可以通过使用新的生产者将数据推送到另一个主题。但是我无法做的是初始化多个消费者以使用同一主题。
在appsettings.json中:
ahsansLayout.xml
processOrderServices.cs:
"consumer": {
"bootstrapservers": "localhost:9092", //specify your kafka broker address
"groupid": "csharp-consumer",
"enableautocommit": true,
"statisticsintervalms": 5000,
"sessiontimeoutms": 6000,
"autooffsetreset": 0,
"enablepartitioneof": true,
"SaslMechanism": 0, //0 for GSSAPI
//"SaslKerberosKeytab":"filename.keytab", //specify your keytab file here
"SaslKerberosPrincipal": "youralias@DOMAIN.COM", //specify your alias here
"SaslKerberosServiceName": "kafka"
//"SaslKerberosKinitCmd":"kinit -k -t %{sasl.kerberos.keytab} %{sasl.kerberos.principal}"
},
ConsumerWrapper.cs:
namespace Api.Services
{
public class ProcessOrdersService : BackgroundService
{
private readonly ConsumerConfig consumerConfig;
private readonly ProducerConfig producerConfig;
//----------------------
//private readonly ConsumerConfig consumerConfig2;
public ProcessOrdersService(ConsumerConfig consumerConfig, ProducerConfig producerConfig)
{
this.producerConfig = producerConfig;
this.consumerConfig = consumerConfig;
//----------------------
//this.consumerConfig2 = consumerConfig;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("OrderProcessing Service Started\n\n");
while (!stoppingToken.IsCancellationRequested)
{
var consumerHelper = new ConsumerWrapper(consumerConfig, "orderrequests");
//var consumerHelper2 = new ConsumerWrapper(consumerConfig, "orderrequests");
string orderRequest = consumerHelper.readMessage();
//consumerHelper2.DisplayMessage();
//Deserilaize
OrderRequest order = JsonConvert.DeserializeObject<OrderRequest>(orderRequest);
//TODO:: Process Order
Console.WriteLine($"Info: OrderHandler => Processing the order for {order.productname}\n\n");
order.status = OrderStatus.COMPLETED;
//Write to ReadyToShip Queue
var producerWrapper = new ProducerWrapper(producerConfig,"readytoship");
await producerWrapper.writeMessage(JsonConvert.SerializeObject(order));
//--------------------------
// var consumerHelper2 = new ConsumerWrapper(consumerConfig2, "orderrequests");
//string processedOrder = consumerHelper2.readMessage();
//OrderRequest order2 = JsonConvert.DeserializeObject<OrderRequest>(processedOrder);
//Console.WriteLine($"Info: OrderHandler => Delivered the order for {order2.productname}\n\n");
//order2.status = OrderStatus.DELIVERED;
//----------------------------
}
}
}
}
我希望能够多次调用Consumer类并能够读取相同的主题。我知道,为了能够做到这一点,需要创建多个分区/组ID。但是我无法弄清楚在哪里以及如何去做。
答案 0 :(得分:0)
您可以通过在Kafka中使用组ID概念来做到这一点,只需对多个使用者使用相同的组ID,即可避免重复使用同一主题中的数据。