74 lines
2.3 KiB
C#
Raw Normal View History

2025-04-09 14:33:20 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Confluent.Kafka;
2025-04-12 15:11:18 +08:00
using JiShe.CollectBus.Kafka.Consumer;
2025-04-09 14:33:20 +08:00
using Microsoft.Extensions.Configuration;
2025-04-12 15:11:18 +08:00
using Microsoft.Extensions.Logging;
2025-04-09 14:33:20 +08:00
using Volo.Abp.DependencyInjection;
namespace JiShe.CollectBus.Kafka.Producer
{
2025-04-12 15:11:18 +08:00
public class ProducerService<TKey, TValue> : IProducerService<TKey, TValue>, IDisposable,ITransientDependency
2025-04-09 14:33:20 +08:00
{
2025-04-12 15:11:18 +08:00
private readonly ILogger<ConsumerService<TKey, TValue>> _logger;
2025-04-09 14:33:20 +08:00
2025-04-12 15:11:18 +08:00
protected ProducerService(IConfiguration configuration, ILogger<ConsumerService<TKey, TValue>> logger)
2025-04-09 14:33:20 +08:00
{
2025-04-12 15:11:18 +08:00
_logger = logger;
GetInstance(configuration);
2025-04-09 14:33:20 +08:00
}
2025-04-12 15:11:18 +08:00
public IProducer<TKey, TValue> Instance { get; set; } = default;
public IProducer<TKey, TValue> GetInstance(IConfiguration configuration)
{
var enableAuthorization = bool.Parse(configuration["Kafka:EnableAuthorization"]);
var consumerConfig = new ProducerConfig
{
BootstrapServers = configuration["Kafka:BootstrapServers"],
AllowAutoCreateTopics = true
};
if (enableAuthorization)
{
consumerConfig.SecurityProtocol = SecurityProtocol.SaslPlaintext;
consumerConfig.SaslMechanism = SaslMechanism.Plain;
consumerConfig.SaslUsername = configuration["Kafka:SaslUserName"];
consumerConfig.SaslPassword = configuration["Kafka:SaslPassword"];
}
Instance = new ProducerBuilder<TKey, TValue>(consumerConfig).Build();
return Instance;
}
public async Task ProduceAsync(string topic, TKey key, TValue value)
{
var message = new Message<TKey, TValue>
{
Key = key,
Value = value
};
await Instance.ProduceAsync(topic, message);
}
public async Task ProduceAsync(string topic, TValue value)
2025-04-09 14:33:20 +08:00
{
2025-04-12 15:11:18 +08:00
var message = new Message<TKey, TValue>
2025-04-09 14:33:20 +08:00
{
2025-04-12 15:11:18 +08:00
Value = value
};
await Instance.ProduceAsync(topic, message);
}
public void Dispose()
{
Instance?.Dispose();
2025-04-09 14:33:20 +08:00
}
}
}