.net core kafka 入门实例 一篇看懂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /// <summary> /// 消费者 /// </summary> public interface IKafkaConsumer : IDisposable { /// <summary> /// 消费数据 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T Consume<T>() where T : class ; } public interface IKafkaProducer : IDisposable { /// <summary> /// 发布消息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="data"></param> /// <param name="operateType"></param> /// <returns></returns> bool Produce<T>( string key, T data, int operateType) where T : class ; } |
实现方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | using Confluent.Kafka; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Kafka { public class KafkaConsumer : IKafkaConsumer { private bool disposeHasBeenCalled = false ; private readonly object disposeHasBeenCalledLockObj = new object (); private readonly IConsumer< string , string > _consumer; /// <summary> /// 构造函数,初始化配置 /// </summary> /// <param name="config">配置参数</param> /// <param name="topic">主题名称</param> public KafkaConsumer(ConsumerConfig config, string topic) { _consumer = new ConsumerBuilder< string , string >(config).Build(); _consumer.Subscribe(topic); } /// <summary> /// 消费 /// </summary> /// <returns></returns> public T Consume<T>() where T : class { try { var result = _consumer.Consume(TimeSpan.FromSeconds(1)); if (result != null ) { if ( typeof (T) == typeof ( string )) return (T)Convert.ChangeType(result.Value, typeof (T)); return JsonConvert.DeserializeObject<T>(result.Value); } } catch (ConsumeException e) { Console.WriteLine($ "consume error: {e.Error.Reason}" ); } catch (Exception e) { Console.WriteLine($ "consume error: {e.Message}" ); } return default ; } /// <summary> /// 释放 /// </summary> public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } /// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> protected virtual void Dispose( bool disposing) { lock (disposeHasBeenCalledLockObj) { if (disposeHasBeenCalled) { return ; } disposeHasBeenCalled = true ; } if (disposing) { _consumer?.Close(); } } }<br><br> } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | public class KafkaProducer : IKafkaProducer { private bool disposeHasBeenCalled = false ; private readonly object disposeHasBeenCalledLockObj = new object (); private readonly IProducer< string , string > _producer; private readonly string _topic; /// <summary> /// 构造函数,初始化配置 /// </summary> /// <param name="config">配置参数</param> /// <param name="topic">主题名称</param> public KafkaProducer(ProducerConfig config, string topic) { _producer = new ProducerBuilder< string , string >(config).Build(); _topic = topic; } /// <summary> /// 发布消息 /// </summary> /// <typeparam name="T">数据实体</typeparam> /// <param name="key">数据key,partition分区会根据key</param> /// <param name="data">数据</param> /// <param name="operateType">操作类型[增、删、改等不同类型]</param> /// <returns></returns> public bool Produce<T>( string key, T data, int operateType) where T : class { var obj = JsonConvert.SerializeObject( new { Type = operateType, Data = data }); try { var result = _producer.ProduceAsync(_topic, new Message< string , string > { Key = key, Value = obj }).ConfigureAwait( false ).GetAwaiter().GetResult(); #if DEBUG Console.WriteLine($ "Topic: {result.Topic} Partition: {result.Partition} Offset: {result.Offset}" ); #endif return true ; } catch (ProduceException< string , string > e) { Console.WriteLine($ "Delivery failed: {e.Error.Reason}" ); } catch (Exception e) { Console.WriteLine($ "Delivery failed: {e.Message}" ); } return false ; } /// <summary> /// 释放 /// </summary> public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } /// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> protected virtual void Dispose( bool disposing) { lock (disposeHasBeenCalledLockObj) { if (disposeHasBeenCalled) { return ; } disposeHasBeenCalled = true ; } if (disposing) { _producer?.Dispose(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | static void Main( string [] args) { var config = new ProducerConfig { BootstrapServers = "localhost:9092" , Acks = Acks.All }; //发送消息 using ( var kafkaProducer = new KafkaProducer(config, "topic-d" )) { var result = kafkaProducer.Produce< object >( "a" , new { name = "猪八戒3" }, 1); } Console.WriteLine( "消息发送成功" ); } static void Main( string [] args) { var config = new ConsumerConfig { BootstrapServers = "localhost:9092" , GroupId = "test" , AutoOffsetReset = AutoOffsetReset.Earliest }; string text; Console.WriteLine( "接受中......" ); while ((text = Console.ReadLine()) != "q" ) { //接受消息 using ( var kafkaProducer = new KafkaConsumer(config, "topic-d" )) { var result = kafkaProducer.Consume< object >(); if (result != null ) { Console.WriteLine(result.ToString()); } } } } |
上结果、
可以看到,消息已经收到了。
欢迎各位转载,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
作者:DanielYao
出处:https://www.cnblogs.com/DanielYao/p/12922745.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
欢迎大家关注我的微信公众号,新文章会优先发到公众号!
本文来自博客园,作者:打滚的姚先森,转载请注明原文链接:https://www.cnblogs.com/DanielYao/p/12922745.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异