Exemplo n.º 1
0
 /// <summary>
 /// 停止消息监听
 /// </summary>
 public void StopMonitorKafkaMessage()
 {
     lock (_msgMonitorStateLock)
     {
         _msgMonitorState = MessageMonitorState.Closed;
         BroadcastMessageMonitorState();
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// 启动消息监听
        /// </summary>
        public void StartMonitorKafkaMessage(string sTopic)
        {
            try
            {
                lock (_msgMonitorStateLock)
                {
                    if (_msgMonitorState != MessageMonitorState.Open)
                    {
                        _msgMonitorState = MessageMonitorState.Open;
                        BroadcastMessageMonitorState();

                        string[] args = new string[] { _conn, sTopic };

                        string brokerList = args[0];
                        var    topics     = args.Skip(1).ToList();

                        var config = new Dictionary <string, object> {
                            { "group.id", "simple-csharp-consumer" },
                            { "bootstrap.servers", brokerList }
                        };

                        using (var consumer = new Consumer <Null, string>(
                                   config, null, new StringDeserializer(Encoding.UTF8)))
                        {
                            consumer.Assign(new List <TopicPartitionOffset> {
                                new TopicPartitionOffset(topics.First(), 0, 0)
                            });

                            while (_msgMonitorState == MessageMonitorState.Open)
                            {
                                Message <Null, string> msg;
                                if (consumer.Consume(out msg, TimeSpan.FromSeconds(1)))
                                {
                                    BroadcastKafkaMessage(msg.Value);
                                    LogHelper.WriteLog($"Topic: {msg.Topic} Partition: {msg.Partition} Offset: {msg.Offset} {msg.Value}");
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(e.ToString());
            }
        }