59 lines
1.5 KiB
C#
Raw Normal View History

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;
public KafkaConsumer(IConfiguration config)
{
2024-12-04 01:57:10 +04:00
_config = config;
ChangeBrokerIp(_config["Kafka:BootstrapServers"]);
}
2024-12-04 01:57:10 +04:00
public IEnumerable<T>? WaitMessages<T>(string topic)
where T : IBrokerResponse
2024-12-04 01:57:10 +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}");
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);
}
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();
}
}
}