Is it safe to re-use an instance of IProducer to call ProduceAsync() from multiple threads?
My use case is an API method in an ASP.NET core application, in which I want to produce a message when the API is called.
[Route( "api/demo/producer" )]
[ApiController]
public class ProducerController : ControllerBase
{
private readonly IProducer<int, string> _kafkaProducer;
public ProducerController( IProducer<int, string> kafkaProducer )
{
_kafkaProducer = kafkaProducer;
}
[HttpPost( "produce" )]
public async Task<string> Produce( [FromBody] int key, [FromBody] string value )
{
var message = new Message<int, string> { Key = key, Value = value };
var result = await _kafkaProducer.ProduceAsync( "test-topic", message );
return $"Delivered '{result.Key}','{result.Value}' to '{result.TopicPartitionOffset}'";
}
}
where the producer instance is injected as a singleton by adding it as a singleton in ConfigureServices() like this:
services.AddSingleton( new ProducerBuilder<int, string> ( config ).Build( ) );
Please provide the following information:
yes
Ok, thanks for the quick answer, may I suggest that this be specifically mentioned in README.md or in the examples?
yes, our documentation is badly lacking. it's on the list.
Most helpful comment
yes, our documentation is badly lacking. it's on the list.