public Task StartAsync(CancellationToken cancellationToken) { var conf = new ConsumerConfig { GroupId = "test-consumer-group", BootstrapServers = "localhost:9092", AutoOffsetReset = AutoOffsetReset.Earliest }; using (var c = new ConsumerBuilder <int, string>(conf).Build()) { c.Subscribe("fila_hello_world"); var cts = new CancellationTokenSource(); try { while (true) { var message = c.Consume(cts.Token); bool success = true; var settings = new JsonSerializerSettings { Error = (sender, args) => { success = false; args.ErrorContext.Handled = true; } }; MessageDto messageObj = JsonConvert.DeserializeObject <MessageDto>(message.Message.Value, settings); int ident = message.Message.Key; _logger.LogInformation("Mensagem: " + messageObj.Message); _logger.LogInformation("ApplicationId: " + messageObj.ApplicationId); _logger.LogInformation("RequestId: " + messageObj.RequestId); _logger.LogInformation("Timestamp: " + messageObj.Timestamp); _logger.LogInformation("Kafka Key: " + ident); } } catch (OperationCanceledException) { c.Close(); } } return(Task.CompletedTask); }
private async void DoWork(object state) { try { _logger.LogInformation("Timed Background Service is working."); var config = new ProducerConfig { BootstrapServers = "localhost:9092" }; using (var producer = new ProducerBuilder <int, string>(config).Build()) { try { MessageDto message = new MessageDto() { ApplicationId = Process.GetCurrentProcess().Id, Message = "Hello World", RequestId = Guid.NewGuid().ToString(), Timestamp = DateTime.Now }; var sendResult = producer .ProduceAsync("fila_hello_world", new Message <int, string> { Key = new Random().Next(int.MaxValue), Value = JsonConvert.SerializeObject(message) }) .GetAwaiter() .GetResult(); } catch (ProduceException <Null, string> e) { Console.WriteLine($"Delivery failed: {e.Error.Reason}"); } } } catch (Exception ex) { _logger.LogError(ex, "Error sending message to Kafka"); } }