65 lines
2.3 KiB
C#
65 lines
2.3 KiB
C#
using Confluent.Kafka;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Volo.Abp.DependencyInjection;
|
|
|
|
namespace JiShe.CollectBus.Kafka.Producer
|
|
{
|
|
public class ProducerBaseService<TKey, TValue>
|
|
{
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="ProducerBaseService{TKey, TValue}"/> class.
|
|
/// </summary>
|
|
/// <param name="configuration">The configuration.</param>
|
|
public ProducerBaseService(IConfiguration configuration)
|
|
{
|
|
GetInstance(configuration);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets or sets the instance.
|
|
/// </summary>
|
|
/// <value>
|
|
/// The instance.
|
|
/// </value>
|
|
public IProducer<TKey, TValue> Instance { get; set; } = default;
|
|
|
|
/// <summary>
|
|
/// Gets the instance.
|
|
/// </summary>
|
|
/// <param name="configuration">The configuration.</param>
|
|
/// <returns></returns>
|
|
public IProducer<TKey, TValue> GetInstance(IConfiguration configuration)
|
|
{
|
|
var enableAuthorization = bool.Parse(configuration["Kafka:EnableAuthorization"]);
|
|
var producerConfig = new ProducerConfig
|
|
{
|
|
BootstrapServers = configuration["Kafka:BootstrapServers"],
|
|
AllowAutoCreateTopics = true,
|
|
};
|
|
|
|
if (enableAuthorization)
|
|
{
|
|
producerConfig.SecurityProtocol = SecurityProtocol.SaslPlaintext;
|
|
producerConfig.SaslMechanism = SaslMechanism.Plain;
|
|
producerConfig.SaslUsername = configuration["Kafka:SaslUserName"];
|
|
producerConfig.SaslPassword = configuration["Kafka:SaslPassword"];
|
|
}
|
|
Instance = new ProducerBuilder<TKey, TValue>(producerConfig).Build();
|
|
return Instance;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Produces the asynchronous.
|
|
/// </summary>
|
|
/// <param name="topic">The topic.</param>
|
|
/// <param name="message">The message.</param>
|
|
/// <param name="cancellationToken">The cancellation token.</param>
|
|
public async Task ProduceAsync(string topic, Message<TKey, TValue> message, CancellationToken cancellationToken = default)
|
|
{
|
|
await Instance.ProduceAsync(topic, message, cancellationToken);
|
|
}
|
|
|
|
|
|
}
|
|
}
|