Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MahdiKarimipour/0b732307573b90fc1781981cf2227b2f to your computer and use it in GitHub Desktop.
Save MahdiKarimipour/0b732307573b90fc1781981cf2227b2f to your computer and use it in GitHub Desktop.
Kafka Event Producer Service
public class KafkaService : IKafkaService
{
private readonly string saslUsername;
private readonly string saslPassword;
public readonly string serverAddress;
public KafkaService(string serverAddress, string saslUsername, string saslPassword)
{
this.serverAddress = serverAddress;
this.saslUsername = saslUsername;
this.saslPassword = saslPassword;
}
public async Task SendMessage(string topic, string message)
{
if (message.IsEmpty())
{
throw new ArgumentNullException(nameof(message));
}
var config = new ProducerConfig
{
BootstrapServers = serverAddress,
SecurityProtocol = SecurityProtocol.SaslSsl,
SaslMechanism = SaslMechanism.Plain,
SaslUsername = saslUsername,
SaslPassword = saslPassword,
Acks = Acks.Leader,
CompressionType = CompressionType.Lz4,
Debug = "security,broker,protocol"
};
using (var producer = new ProducerBuilder<Null, string>(config).Build())
{
await producer.ProduceAsync(topic, new Message<Null, string>
{
Value = message
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment