forked from dotnet/aspire
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsumerWorker.cs
More file actions
41 lines (37 loc) · 1.46 KB
/
ConsumerWorker.cs
File metadata and controls
41 lines (37 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Confluent.Kafka;
namespace Consumer;
internal sealed class ConsumerWorker(IConsumer<Ignore, string> consumer, ILogger<ConsumerWorker> logger) : BackgroundService
{
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
long i = 0;
return Task.Factory.StartNew(async () =>
{
consumer.Subscribe("topic");
while (!stoppingToken.IsCancellationRequested)
{
ConsumeResult<Ignore, string>? result = default;
try
{
result = consumer.Consume(TimeSpan.FromSeconds(1));
if (result is not null)
{
logger.LogInformation($"Consumed message [{result.Message?.Key}] = {result.Message?.Value}");
}
}
catch (ConsumeException ex) when (ex.Error.Code == ErrorCode.UnknownTopicOrPart)
{
await Task.Delay(100);
continue;
}
i++;
if (i % 1000 == 0)
{
logger.LogInformation($"Received {i} messages. current offset is '{result!.Offset}'");
}
}
}, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
}