Сделка в Confluent.Kafka на Потребителя - PullRequest
1 голос
/ 30 июня 2019

Я использую Apache Kafka в качестве обработчика сообщений и использую Confluent.Kafka в Asp.Net Core в качестве потребителя.

Я хочу использовать сообщения и сохранять в базе данных, по-видимомуМне нужна транзакция для подтверждения или отката в очереди

Я использую образец этой библиотеки, как показано ниже:

public static void Main(string[] args)
    {
        var conf = new ConsumerConfig
        {
            GroupId = "test-consumer-group",
            BootstrapServers = "127.0.0.1:9092",
            // Note: The AutoOffsetReset property determines the start offset in the event
            // there are not yet any committed offsets for the consumer group for the
            // topic/partitions of interest. By default, offsets are committed
            // automatically, so in this example, consumption will only start from the
            // earliest message in the topic 'my-topic' the first time you run the program.
            AutoOffsetReset = AutoOffsetReset.Earliest
        };

        using (var c = new ConsumerBuilder<Ignore, string>(conf).Build())
        {
            c.Subscribe("testtopic");

            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress += (_, e) => {
                e.Cancel = true; // prevent the process from terminating.
                cts.Cancel();
            };

            try
            {
                while (true)
                {
                    try
                    {
                        var cr = c.Consume(cts.Token);  // I NEED TRANSACTION HERE...


                        Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'.");
                    }
                    catch (ConsumeException e)
                    {
                        Console.WriteLine($"Error occured: {e.Error.Reason}");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                c.Close();
            }
        }
    }

Что мне делать?

1 Ответ

1 голос
/ 30 июня 2019

По умолчанию Кафка-потребитель «автоматически и периодически фиксирует смещения в фоновом режиме» - это поведение определяется двумя параметрами конфигурации: EnableAutoCommit и AutoCommitIntervalMs .

InВ вашем случае необходимо сделать коммит вручную:

var conf = new ConsumerConfig
{
    // ..
    EnableAutoCommit = false // <-----
};


// ..

    try
    {
        var cr = c.Consume(cts.Token);

        // .. save data to database ..

        c.Commit(); // <-----

        Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'.");
    }
    catch (ConsumeException e)
    {
        Console.WriteLine($"Error occured: {e.Error.Reason}");
    }
...