-
Notifications
You must be signed in to change notification settings - Fork 2
/
ChannelProvider.cs
52 lines (42 loc) · 1.82 KB
/
ChannelProvider.cs
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
42
43
44
45
46
47
48
49
50
51
52
using Confluent.Kafka;
using System.Threading.Channels;
namespace KafkaParallelConsumer;
public sealed class ChannelProvider<TKey, TValue>
{
private readonly Dictionary<TopicPartition, Channel<ConsumeResult<TKey, TValue>>> channels;
private readonly Dictionary<TopicPartition, Task> workers;
public ChannelProvider()
{
this.channels = new Dictionary<TopicPartition, Channel<ConsumeResult<TKey, TValue>>>();
this.workers = new Dictionary<TopicPartition, Task>();
}
public void CreateTopicPartitionChannel(TopicPartition topicPartition)
{
if (!channels.ContainsKey(topicPartition))
{
var channel = Channel.CreateUnbounded<ConsumeResult<TKey, TValue>>(new UnboundedChannelOptions()
{
AllowSynchronousContinuations = false,
SingleReader = true,
SingleWriter = true,
});
channels.Add(topicPartition, channel);
}
}
public ChannelWriter<ConsumeResult<TKey, TValue>> GetChannelWriter(IConsumer<TKey, TValue> consumer, TopicPartition topicPartition,
Func<ConsumeResult<TKey, TValue>, CancellationToken, Task> processingAction, CancellationToken cancellationToken)
{
var channel = channels[topicPartition];
if (!workers.ContainsKey(topicPartition))
{
var topicWorker = new TopicPartitionWorker<TKey, TValue>(consumer, channel.Reader, processingAction, commitSynchronous: false);
workers.Add(topicPartition, topicWorker.ExecuteAsync(cancellationToken));
}
return channel.Writer;
}
public void CompleteTopicPartitionChannel(TopicPartition topicPartition)
{
var channel = channels[topicPartition];
channel.Writer.Complete();
}
}