forked from confluentinc/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
184 lines (161 loc) · 6.76 KB
/
Program.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Copyright 2020 Confluent Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Confluent.Kafka;
using Confluent.Kafka.Admin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CCloud
{
class Program
{
static async Task<ClientConfig> LoadConfig(string configPath, string certDir)
{
try
{
var cloudConfig = (await File.ReadAllLinesAsync(configPath))
.Where(line => !line.StartsWith("#"))
.ToDictionary(
line => line.Substring(0, line.IndexOf('=')),
line => line.Substring(line.IndexOf('=') + 1));
var clientConfig = new ClientConfig(cloudConfig);
if (certDir != null)
{
clientConfig.SslCaLocation = certDir;
}
return clientConfig;
}
catch (Exception e)
{
Console.WriteLine($"An error occured reading the config file from '{configPath}': {e.Message}");
System.Environment.Exit(1);
return null; // avoid not-all-paths-return-value compiler error.
}
}
static async Task CreateTopicMaybe(string name, int numPartitions, short replicationFactor, ClientConfig cloudConfig)
{
using (var adminClient = new AdminClientBuilder(cloudConfig).Build())
{
try
{
await adminClient.CreateTopicsAsync(new List<TopicSpecification> {
new TopicSpecification { Name = name, NumPartitions = numPartitions, ReplicationFactor = replicationFactor } });
}
catch (CreateTopicsException e)
{
if (e.Results[0].Error.Code != ErrorCode.TopicAlreadyExists)
{
Console.WriteLine($"An error occured creating topic {name}: {e.Results[0].Error.Reason}");
}
else
{
Console.WriteLine("Topic already exists");
}
}
}
}
static void Produce(string topic, ClientConfig config)
{
using (var producer = new ProducerBuilder<string, string>(config).Build())
{
int numProduced = 0;
int numMessages = 10;
for (int i=0; i<numMessages; ++i)
{
var key = "alice";
var val = JObject.FromObject(new { count = i }).ToString(Formatting.None);
Console.WriteLine($"Producing record: {key} {val}");
producer.Produce(topic, new Message<string, string> { Key = key, Value = val },
(deliveryReport) =>
{
if (deliveryReport.Error.Code != ErrorCode.NoError)
{
Console.WriteLine($"Failed to deliver message: {deliveryReport.Error.Reason}");
}
else
{
Console.WriteLine($"Produced message to: {deliveryReport.TopicPartitionOffset}");
numProduced += 1;
}
});
}
producer.Flush(TimeSpan.FromSeconds(10));
Console.WriteLine($"{numProduced} messages were produced to topic {topic}");
}
}
static void Consume(string topic, ClientConfig config)
{
var consumerConfig = new ConsumerConfig(config);
consumerConfig.GroupId = "dotnet-example-group-1";
consumerConfig.AutoOffsetReset = AutoOffsetReset.Earliest;
consumerConfig.EnableAutoCommit = false;
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => {
e.Cancel = true; // prevent the process from terminating.
cts.Cancel();
};
using (var consumer = new ConsumerBuilder<string, string>(consumerConfig).Build())
{
consumer.Subscribe(topic);
var totalCount = 0;
try
{
while (true)
{
var cr = consumer.Consume(cts.Token);
totalCount += JObject.Parse(cr.Message.Value).Value<int>("count");
Console.WriteLine($"Consumed record with key {cr.Message.Key} and value {cr.Message.Value}, and updated total count to {totalCount}");
}
}
catch (OperationCanceledException)
{
// Ctrl-C was pressed.
}
finally
{
consumer.Close();
}
}
}
static void PrintUsage()
{
Console.WriteLine("usage: .. produce|consume <topic> <configPath> [<certDir>]");
System.Environment.Exit(1);
}
static async Task Main(string[] args)
{
if (args.Length != 3 && args.Length != 4) { PrintUsage(); }
var mode = args[0];
var topic = args[1];
var configPath = args[2];
var certDir = args.Length == 4 ? args[3] : null;
var config = await LoadConfig(configPath, certDir);
switch (mode)
{
case "produce":
await CreateTopicMaybe(topic, 1, 3, config);
Produce(topic, config);
break;
case "consume":
Consume(topic, config);
break;
default:
PrintUsage();
break;
}
}
}
}