2024-11-19 23:23:21 +04:00
|
|
|
|
|
|
|
using Cloud.Services.Broker.Support;
|
|
|
|
using Confluent.Kafka;
|
|
|
|
using System.Text.Json;
|
|
|
|
|
|
|
|
namespace Cloud.Services.Broker.Implement.Kafka
|
|
|
|
{
|
|
|
|
public class KafkaConsumer : IBrokerConsumer
|
|
|
|
{
|
2024-12-04 01:57:10 +04:00
|
|
|
private IConsumer<string, string> _consumer;
|
|
|
|
private readonly IConfiguration _config;
|
2024-11-19 23:23:21 +04:00
|
|
|
|
|
|
|
public KafkaConsumer(IConfiguration config)
|
|
|
|
{
|
2024-12-04 01:57:10 +04:00
|
|
|
_config = config;
|
|
|
|
ChangeBrokerIp(_config["Kafka:BootstrapServers"]);
|
2024-11-19 23:23:21 +04:00
|
|
|
}
|
|
|
|
|
2024-12-04 01:57:10 +04:00
|
|
|
public IEnumerable<T>? WaitMessages<T>(string topic)
|
2024-11-19 23:23:21 +04:00
|
|
|
where T : IBrokerResponse
|
2024-12-04 01:57:10 +04:00
|
|
|
{
|
2024-11-19 23:23:21 +04:00
|
|
|
try
|
|
|
|
{
|
|
|
|
_consumer.Subscribe(topic);
|
|
|
|
|
|
|
|
var consumeResult = _consumer.Consume(TimeSpan.FromMilliseconds(1000));
|
2024-12-04 01:57:10 +04:00
|
|
|
Console.WriteLine($"================ Received message: {consumeResult?.Message.Value}");
|
2024-11-19 23:23:21 +04:00
|
|
|
if (consumeResult == null)
|
|
|
|
{
|
|
|
|
// No message received from Kafka within the specified timeout.
|
|
|
|
return default;
|
|
|
|
}
|
2024-12-04 01:57:10 +04:00
|
|
|
|
|
|
|
return JsonSerializer.Deserialize<IEnumerable<T>>(consumeResult.Message.Value);
|
2024-11-19 23:23:21 +04:00
|
|
|
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
throw;
|
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
|
|
|
_consumer.Close();
|
|
|
|
}
|
|
|
|
}
|
2024-12-04 01:57:10 +04:00
|
|
|
|
|
|
|
public void ChangeBrokerIp(string ip)
|
|
|
|
{
|
|
|
|
var consumerConfig = new ConsumerConfig()
|
|
|
|
{
|
|
|
|
BootstrapServers = ip,
|
|
|
|
GroupId = _config["Kafka:GroupId"],
|
|
|
|
AutoOffsetReset = AutoOffsetReset.Earliest,
|
|
|
|
};
|
|
|
|
|
|
|
|
_consumer = new ConsumerBuilder<string, string>(consumerConfig).Build();
|
|
|
|
}
|
2024-11-19 23:23:21 +04:00
|
|
|
}
|
|
|
|
}
|