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();
                }
            }
        }
    }
}

运行效果:

相关推荐
JAVA学习通16 分钟前
【RabbitMQ】---RabbitMQ 工作流程和 web 界面介绍
分布式·rabbitmq
cg.family28 分钟前
Doris 消费kafka消息
kafka·doris
安卓开发者1 小时前
鸿蒙NEXT应用数据持久化全面解析:从用户首选项到分布式数据库
数据库·分布式·harmonyos
趴着喝可乐2 小时前
openEuler2403安装部署Kafka
kafka·openeuler
JAVA学习通4 小时前
【RabbitMQ】如何在 Ubuntu 安装 RabbitMQ
分布式·rabbitmq
Lansonli4 小时前
大数据Spark(六十三):RDD-Resilient Distributed Dataset
大数据·分布式·spark
BYSJMG5 小时前
计算机毕业设计选题:基于Spark+Hadoop的健康饮食营养数据分析系统【源码+文档+调试】
大数据·vue.js·hadoop·分布式·spark·django·课程设计
JAVA学习通5 小时前
【RabbitMQ】----RabbitMQ 的7种工作模式
分布式·rabbitmq
励志成为糕手6 小时前
Hadoop进程:深入理解分布式计算引擎的核心机制
大数据·hadoop·分布式·mapreduce·yarn
掘金-我是哪吒6 小时前
分布式微服务系统架构第170集:Kafka消费者并发-多节点消费-可扩展性
分布式·微服务·架构·kafka·系统架构