Kafka生产者与消费者(C#编辑)在Kafka上的实现

首先

由于似乎要使用Kafka,因此尝试为几种语言编写生产者和消费者的代码。

上一次尝试了Golang,上上一次则是试了一下Scala。

这次我们来介绍C#编程。在C#中,我们将尝试使用之前无法在Golang中试用的confluent-kafka-dotnet插件(这个插件已经包含在NuGet中,因此不需要直接安装librdkafka)。

* 本次不会对卡夫卡的作品进行解说。

构成

VisualStudio:2017
.NET Framework:4.5
confluent-kafka-dotnet:0.11
Newtonsoft.Json:11.0

VisualStudio:2017年版
.NET Framework:4.5版本
confluent-kafka-dotnet:0.11版本
Newtonsoft.Json:11.0版本

VisualStudio:2017版
.NET Framework:4.5版
confluent-kafka-dotnet:0.11版
Newtonsoft.Json:11.0版

完成的产品/结果

项目创建和NuGet

首先,创建一个新的标准控制台应用程序,然后通过NuGet包管理来安装”Confluent.Kafka”和”Newtonsoft.Json”用于消息的序列化和反序列化。

消息对象

我会定义发送和接收消息。内容和上次一样。

namespace DotNetKafkaExample
{
    // 送信メッセージ
    class SendMessage
    {
        public string Message { get; set; }

        public long Timestamp { get; set; }

    }

    // 受信メッセージ
    class ConsumedMessage
    {
        public string Message { get; set; }

        public long Timestamp { get; set; }

    }
}

制片人

首先,我会参考制作人提供的例子来尝试写作。

// usingは省略

namespace DotNetKafkaExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("please input bootstrap servers.");

            var bootstrapServers = Console.ReadLine();

            // Taskキャンセルトークン
            var tokenSource = new CancellationTokenSource();

            Console.WriteLine($"start .Net Kafka Example. Ctl+C to exit");

            // プロデューサータスク
            var pTask = Task.Run(() => new Action<string, CancellationToken>(async (bs, cancel) =>
            {
                var cf = new Dictionary<string, object> {
                    { "bootstrap.servers", bs }
                };

                using (var producer = new Producer<string, string>(cf, new StringSerializer(Encoding.UTF8), new StringSerializer(Encoding.UTF8)))
                {
                    producer.OnError += (_, error) => Console.WriteLine($"fail send. reason: {error.Reason}");

                    while (true)
                    {
                        if (cancel.IsCancellationRequested)
                        {
                            break;
                        }

                        var timestamp = DateTime.UtcNow.ToBinary();

                        var pa = producer.ProduceAsync("test.C", timestamp.ToString(), JsonConvert.SerializeObject(new SendMessage
                        {
                            Message = "Hello",
                            Timestamp = timestamp
                        }));

                        await pa.ContinueWith(t => Console.WriteLine($"success send. message: {t.Result.Value}"));
                        await Task.Delay(10000);
                    }

                    // 停止前処理
                    producer.Flush(TimeSpan.FromMilliseconds(10000));
                }
            })(bootstrapServers, tokenSource.Token), tokenSource.Token);

            // Ctl+C待機
            Console.CancelKeyPress += (_, e) =>
            {
                e.Cancel = true;
                tokenSource.Cancel(); // Taskキャンセル
            };

            Task.WaitAll(pTask, cTask);

            Console.WriteLine("stop .Net Kafka Example. press any key to close.");

            Console.ReadKey();
        }
    }
}

与之前不同,Kafka的地址现在通过控制台接收。将生产者的行为转化为任务,并每隔10秒发送一条消息。等待控制台的“Ctrl+C”命令并通过CancellationTokenSource发送取消通知。
很久没有写C#了,对于闭包的处理有点迷糊……。

消费者

接下来,我将以同样的例子为参考来写一个关于消费者的部分。

// usingは省略

namespace DotNetKafkaExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("please input bootstrap servers.");

            var bootstrapServers = Console.ReadLine();

            // Taskキャンセルトークン
            var tokenSource = new CancellationTokenSource();

            Console.WriteLine($"start .Net Kafka Example. Ctl+C to exit");

            // コンシューマータスク
            var cTask = Task.Run(() => new Action<string, CancellationToken>((bs, cancel) =>
            {
                var cf = new Dictionary<string, object> {
                    { "bootstrap.servers", bs },
                    { "group.id", "test" },
                    { "enable.auto.commit", false },
                    { "default.topic.config", new Dictionary<string, object>()
                        {
                            { "auto.offset.reset", "earliest" }
                        }
                    }
                };

                using (var consumer = new Consumer<string, string>(cf, new StringDeserializer(Encoding.UTF8), new StringDeserializer(Encoding.UTF8)))
                {
                    consumer.OnError += (_, error) => Console.WriteLine($"consumer error. reason: {error.Reason}");

                    consumer.OnConsumeError += (_, error) => Console.WriteLine($"fail consume. reason: {error.Error}");

                    consumer.OnPartitionsAssigned += (_, partitions) => consumer.Assign(partitions);

                    consumer.OnPartitionsRevoked += (_, partitions) => consumer.Unassign();

                    consumer.Subscribe("test.C");

                    while (true)
                    {
                        if (cancel.IsCancellationRequested)
                        {
                            break;
                        }

                        Message<string, string> msg;
                        if (!consumer.Consume(out msg, TimeSpan.FromMilliseconds(100)))
                        {
                            continue;
                        }

                        var cm = JsonConvert.DeserializeObject<ConsumedMessage>(msg.Value);
                        Console.WriteLine($"success consumed. message: {cm.Message}, timestamp: {cm.Timestamp}");

                        consumer.CommitAsync(msg);
                    }
                }
            })(bootstrapServers, tokenSource.Token), tokenSource.Token);

            // Ctl+C待機
            Console.CancelKeyPress += (_, e) =>
            {
                e.Cancel = true;
                tokenSource.Cancel(); // Taskキャンセル
            };

            Task.WaitAll(pTask, cTask);

            Console.WriteLine("stop .Net Kafka Example. press any key to close.");

            Console.ReadKey();
        }
    }
}

总的来说,与制作人类似的感觉,但似乎消费者能接收到更多的事件。
“consumer.Consume(out msg, TimeSpan.FromMilliseconds(100))”是接收部分。

执行

我会像之前一样组合生产者和消费者来执行(Program.cs)。
感觉有时消费者的接收处理比生产者的处理结果输出更快。
*Your.Kafka.Server:9092是虚拟的。

please input bootstrap servers.
Your.Kafka.Server:9092 // ダミー
start .Net Kafka Example. Ctl+C to exit
success send. message: {"Message":"Hello","Timestamp":5248282179105326175}
success consumed. message: Hello, timestamp: 5248282179105326175
success consumed. message: Hello, timestamp: 5248282179235972765
success send. message: {"Message":"Hello","Timestamp":5248282179235972765}
success consumed. message: Hello, timestamp: 5248282179346466796
success send. message: {"Message":"Hello","Timestamp":5248282179346466796}
stop .Net Kafka Example. press any key to close.

终结

我們一直在一個相對封閉的世界中進行,但當我們想要連接到外部時,該如何在C#中做到呢?也許可以嘗試使用RX等工具創建可觀察的生產者和消費者模式。