using Confluent.Kafka;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using TelpoPush.Models.Config;
namespace TelpoPush.Service.Mq.Kafka
{
///
/// 消息生产者
///
public class MessageProducer
{
private readonly ILogger _logger;
private readonly ServiceConfig _configService;
private readonly IProducer _producer;
public MessageProducer(ILogger logger, IOptions optConfigService)
{
_logger = logger;
_configService = optConfigService.Value;
var config = new ProducerConfig
{
BootstrapServers = _configService.KafkaBootstrapServers,
EnableIdempotence = true,
Acks = Acks.All,
//LingerMs=5000,
//BatchNumMessages =1000,
//BatchSize=32768,
//CompressionType= CompressionType.Lz4,
MessageSendMaxRetries = 3
};
_producer = new ProducerBuilder(config).Build();
}
public Headers CreateHeader(Dictionary pair = null)
{
if (pair == null)
{
return null;
}
else
{
Headers headers = new Headers();
foreach (var item in pair)
{
headers.Add(item.Key, BitConverter.GetBytes(item.Value));
}
return headers;
}
}
public async Task ProduceAsync(List topic, object message)
{
try
{
foreach (var item in topic)
{
// producer = new ProducerBuilder(config).Build();
await _producer.ProduceAsync(item.Topic, new Message
{
Headers = item.Headers,
Value = JsonConvert.SerializeObject(message)
});
}
}
catch (ProduceException e)
{
_logger.LogError($"推送到kafka失败,topic: {topic},\n message:{JsonConvert.SerializeObject(message)}: \n{e.Error.Reason}");
}
}
}
}