C# Confluent.Kafka1.2.1 生产者&消费者

C# Confluent.Kafka1.2.1 生产者&消费者

生产者

private IProducer<string, string> _producer = null;
public IProducer<string, string> GetProducerBuilder()
        {
            if (_producer == null)
            {
                var conf = new ProducerConfig
                {
                    BootstrapServers = _YourIP,
                    MessageMaxBytes = 100000000
                };
                _producer = new ProducerBuilder<string, string>(conf).Build();
                return _producer;
            }
            else
            {
                return _producer;
            }
        }
        
        /// <summary>
        /// kafka发送消息
        /// </summary>
        /// <param name="msgKey">消息的key,用于kafka消息分区</param>
        /// <param name="methodName">调用方的方法名,用于区别消息类型进行限制发送条数</param>
        /// <param name="strTopic">kafka的topic</param>
        /// <param name="shortName">消息来源以及发送时间信息</param>
        /// <param name="strJsonData">消息主体</param>
        /// <param name="toTarGz">是否压缩发送</param>
        /// <param name="isSaveFile">是否保存文件</param>        
        public async void UpLoadKafkaMsg(
            string msgKey,
            string methodName,
            string strTopic,
            string shortName,
            string strJsonData,
            bool toTarGz,
            bool isSaveFile = false)
        {
            string strLastRes = strJsonData;
            Byte[] byPckData = null;
            if (GetOpTarGz(toTarGz))
            {
                byPckData = Global.TarCompress(Encoding.UTF8.GetBytes(strJsonData), shortName);
                strLastRes = Convert.ToBase64String(byPckData);
            }

            if (isSaveFile)
            {
                byPckData = Global.TarCompress(Encoding.UTF8.GetBytes(strJsonData), shortName);
                // 输出压缩后的文件检测(重要节点测试代码,本注释代码不能删除)+++++++++++++++++++++++++++++++++++++++++
                string path = Path.Combine(GlobalDefine.AppPath, "KafkaUpLoad");
                Directory.CreateDirectory(path);
                FileStream fs =
                    new FileStream(GlobalDefine.AppPath + @"\KafkaUpLoad\" + shortName + ".tar.gz", FileMode.Create);
                fs.Write(byPckData, 0, byPckData.Length);
                fs.Close();
                // --------------------------------------------------------------------------------------------------
            }

            await Task.Run(() =>
            {
                try
                {
                    Action<DeliveryReport<string, string>> handler = r =>
                    ShowMsg(eMsgType.Send, !r.Error.IsError
                       ? $"Delivered message to {r.TopicPartitionOffset}"
                       : $"Delivery Error: {r.Error.Reason}");

                    var p = GetProducerBuilder();
                    Task<DeliveryResult<string, string>> task = 
                    p.ProduceAsync(strTopic, new Message<string, string> { Key = msgKey, Value = strLastRes });//kafka协议数据发送
                    if(task.Exception == null)
                    {
                        ShowMsg(eMsgType.Send, "kafka成功,主题:" + strTopic, true);
                    }
                    // wait for up to 10 seconds for any inflight messages to be delivered.
                    p.Flush(TimeSpan.FromSeconds(10));
                }
                catch (Exception exception)
                {
                    ShowMsg(eMsgType.Send, "kafka发送失败:" + exception.ToString(), false);
                }
            });
        }

消费者

public async void DownLoadKafkaMsg()
        {
            var config = new ConsumerConfig
            {
                BootstrapServers = _YourIP,
                GroupId = "test-consumer-group",
                AutoOffsetReset = AutoOffsetReset.Latest
            };

            using (var consumer = new ConsumerBuilder<Ignore, string>(config).SetPartitionsAssignedHandler((f, ps) =>
            {
                return ps.Select(tp => new TopicPartitionOffset(tp, f.QueryWatermarkOffsets(tp, TimeSpan.FromSeconds(10)).High));
            }).Build())
            {
                consumer.Subscribe(ThemeCmd);
                ShowMsg(eMsgType.Other, "启动Kafka命令信息消费者");
                CancellationTokenSource cts = new CancellationTokenSource();
                Console.CancelKeyPress += (_, e) =>
                {
                    e.Cancel = true; // prevent the process from terminating.
                    cts.Cancel();
                };
                try
                {
                    while (true)
                    {
                        await Task.Run(() =>
                        {
                            try
                            {
                                var cr = consumer.Consume(cts.Token);
                                string CurrentMessage =
                                    string.Format("Consumed message {0} at {1}", cr.Value, cr.TopicPartitionOffset);
                                // Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'.");
                                PrRegDCIMYK(JsonDeserialize<JRecvCmd>(cr.Value));
                            }
                            catch (ConsumeException e)
                            {
                                Console.WriteLine($"Error occured: {e.Error.Reason}");
                            }
                        });
                    }
                }
                catch (OperationCanceledException)
                {
                    ShowMsg(eMsgType.Other, "Kafka命令信息消费者异常关闭", false);
                    // Ensure the consumer leaves the group cleanly and final offsets are committed.
                    consumer.Close();
                }
            }
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值