当前位置: 首页 > article >正文

netcore Kafka

一、新建项目KafakDemo

  <ItemGroup>
    <PackageReference Include="Confluent.Kafka" Version="2.6.0" />
  </ItemGroup>

二、Program.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();
                }
            }
        }
    }
}

运行效果:

 


http://www.kler.cn/a/403495.html

相关文章:

  • 【SQL 实现计算已历完整月份不同日期的场景】
  • JDK安装和Linux常见设置详细版教程
  • springboot第82集:消息队列kafka,kafka-map
  • VRT: 关于视频修复的模型
  • 佛山三水戴尔R740服务器黄灯故障处理
  • 使用docker compose安装部署gitlab
  • SQL 数据库管理:提升数据管理效率的关键
  • 【ChatGPT】如何通过角色扮演让ChatGPT回答更贴合实际场景
  • Android 功耗分析(底层篇)
  • 微服务即时通讯系统的实现(客户端)----(4)
  • CPU和GPU有什么区别,玩游戏哪个更重要?
  • 提升工作效率的好用的IDEA插件
  • C#编程:免费PDF小工具(可下载)更新功能
  • Vue 3集成海康Web插件实现视频监控
  • Ruby Socket 编程
  • ✅DAY31 贪心算法终 | 56. 合并区间 | 738.单调递增的数字
  • React Native 基础
  • 2025蓝桥杯(单片机)备赛--扩展外设之I2C的重要应用--AT24C02(七)
  • 快速删除 node_modules 目录的集中方法
  • 《原子操作:程序世界里的“最小魔法单位”解析》