Beispiel #1
0
        /// <inheritdoc />
        public async Task SendAsync(TMessage value, CancellationToken cancellation = default)
        {
            var producer = _producerProvider.GetProducer <TMessage>();
            var topic    = _topicProvider.GetTopic <TMessage>();

            var message = new Message <Null, TMessage>
            {
                Value     = value,
                Timestamp = new Timestamp(DateTime.UtcNow)
            };

            await producer.ProduceAsync(topic, message, cancellation);
        }
Beispiel #2
0
        /// <inheritdoc />
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var topic = _topicProvider.GetTopic <TMessage>();

            _consumer.Subscribe(topic);

            while (true)
            {
                if (stoppingToken.IsCancellationRequested)
                {
                    return;
                }

                var result = await Task.Run(() =>
                {
                    try
                    {
                        return(_consumer.Consume(stoppingToken));
                    }
                    catch (ConsumeException ce)
                    {
                        _logger.LogError(ce, "Kafka consumer failed with exception");

                        return(null);
                    }
                }, stoppingToken);

                if (result == null)
                {
                    continue;
                }

                var transportConsumers = _serviceProvider.GetServices <ITransportConsumer <TMessage> >();
                foreach (var transportConsumer in transportConsumers)
                {
                    try
                    {
                        _logger.LogInformation($"Consuming message of type '{typeof(TMessage).Name}'...");
                        await transportConsumer.ConsumeAsync(result.Message.Value, stoppingToken);

                        _logger.LogInformation($"Message of type '{typeof(TMessage).Name}' consumed.");
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e,
                                         $"Exception occured on consuming message of type '{typeof(TMessage).Name}'");
                    }
                }
            }
        }