不同线程使用 Kafka Producer

Using Kafka Producer by different threads

我的基于 java 的 Web 应用程序有 kafka 生产者,用于将消息推送到 Kafka。根据文档,我可以看到 kafka 生产者是线程安全的。这是否意味着我可以拥有 Kafka 生产者的单个实例并由不同的线程(网络请求)使用它,在我的情况下,每个线程都会打开和关闭生产者。这会产生任何问题吗?或者更好地根据请求启动生产者?

到目前为止,最好的方法(这是大多数有状态客户端连接器的典型做法,例如 SQL 客户端、elasticsearch 客户端等)是在应用程序启动时实例化单个实例并在所有线程中共享它。它应该只在应用程序关闭时关闭。

年,KafkaProducer 是线程安全的。
参考Class KafkaProducer

A Kafka client that publishes records to the Kafka cluster.

The producer is thread safe and should generally be shared among all threads for best performance.

The producer manages a single background thread that does I/O as well as a TCP connection to each of the brokers it needs to communicate with. Failure to close the producer after use will leak these resources.