netcore Kafka

一、新建项目KafakDemo

复制代码
  <ItemGroup>
    <PackageReference Include="Confluent.Kafka" Version="2.6.0" />
  </ItemGroup>

二、Program.cs

cs 复制代码
using Confluent.Kafka;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace KafakDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Task.Run(() =>
            {
                Publish();
            });
            Task.Run(() =>
            {
                Consumer();
            });
            Console.ReadKey();
        }

        static void Publish() {

            var conf = new ProducerConfig { BootstrapServers = "192.168.31.135:9092" };

            Action<DeliveryReport<Null, string>> handler = r =>
                        Console.WriteLine(!r.Error.IsError
                             ? $"Delivered message to {r.TopicPartitionOffset}"
                             : $"Delivery Error: {r.Error.Reason}");

            while (true)
            {
                using (var p = new ProducerBuilder<Null, string>(conf).Build())
                {
                    for (int i = 0; i < 1; ++i)
                    {
                        p.Produce("my-topic", new Message<Null, string> { Value = i.ToString() }, handler);
                    }
                    p.Flush();
                }
                Thread.Sleep(TimeSpan.FromSeconds(2));
            }
       
        }

        static void Consumer()
        {
            var conf = new ConsumerConfig
            {
                GroupId = "test-consumer-group",
                BootstrapServers = "192.168.31.135:9092"
                // Note: The AutoOffsetReset property determines the start offset in the event
                // there are not yet any committed offsets for the consumer group for the
                // topic/partitions of interest. By default, offsets are committed
                // automatically, so in this example, consumption will only start from the
                // earliest message in the topic 'my-topic' the first time you run the program.
                //AutoOffsetReset = AutoOffsetReset.Earliest
            };

            using (var c = new ConsumerBuilder<Ignore, string>(conf).Build())
            {
                c.Subscribe("my-topic");

                CancellationTokenSource cts = new CancellationTokenSource();
                Console.CancelKeyPress += (_, e) => {
                    // Prevent the process from terminating.
                    e.Cancel = true;
                    cts.Cancel();
                };

                try
                {
                    while (true)
                    {
                        try
                        {
                            var cr = c.Consume(cts.Token);
                            Console.WriteLine($"Consumed message '{cr.Message.Value}' at: '{cr.TopicPartitionOffset}'.");
                        }
                        catch (ConsumeException e)
                        {
                            Console.WriteLine($"Error occured: {e.Error.Reason}");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // Ensure the consumer leaves the group cleanly and final offsets are committed.
                    c.Close();
                }
            }
        }
    }
}

运行效果:

相关推荐
墨北小七1 小时前
小说大模型的分布式训练——张量并行架构设计与实现
分布式
豆豆2 小时前
政务服务平台站群一体化解决方案
大数据·分布式·微服务·cms·政务·网站管理系统·站群cms
昵称暂无12 小时前
分布式事务难题:Seata框架在微服务中的落地实践
分布式·微服务·架构
都说名字长不会被发现3 小时前
分布式场景下的数据竞争问题与解决方案
分布式·乐观锁·悲观锁·redission·redis 分布式锁·数据版本
甘露s3 小时前
分布式与可重入性的一些问题
分布式
juniperhan3 小时前
Flink 系列第 3 篇:核心概念精讲|分布式缓存 + 重启策略 + 并行度 底层原理 + 代码实战 + 生产规范
大数据·分布式·缓存·flink
想你依然心痛3 小时前
HarmonyOS 5.0 IoT开发实战:构建分布式智能设备控制中枢与边缘计算网关
分布式·物联网·harmonyos
talen_hx2963 小时前
《kafka核心源码解读》学习笔记 Day 02
笔记·学习·kafka
lifallen3 小时前
如何保证 Kafka 的消息顺序性?
java·大数据·分布式·kafka
真实的菜3 小时前
Kafka 2.x vs 3.x,我为什么选择升级?
kafka