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

运行效果:

相关推荐
小马爱打代码7 小时前
SpringBoot原生实现分布式MapReduce计算
spring boot·分布式·mapreduce
南客先生7 小时前
互联网大厂Java面试:RocketMQ、RabbitMQ与Kafka的深度解析
java·面试·kafka·rabbitmq·rocketmq·消息中间件
悻运8 小时前
如何配置Spark
大数据·分布式·spark
懒惰的橘猫8 小时前
Spark集群搭建之Yarn模式
大数据·分布式·spark
2401_824256868 小时前
Spark-Streaming
大数据·分布式·spark
知其_所以然9 小时前
如何使用@KafkaListener实现从nacos中动态获取监听的topic
kafka
淋一遍下雨天10 小时前
Spark-Streaming核心编程
大数据·kafka
爱吃泡芙的小白白13 小时前
爬虫学习——使用HTTP服务代理、redis使用、通过Scrapy实现分布式爬取
redis·分布式·爬虫·http代理·学习记录
樟小叶_公众号同名13 小时前
Kafka运维经验
后端·kafka
小名叫咸菜14 小时前
flume整合Kafka和spark-streaming核心编程
kafka·flume