【问题标题】:Multiple Kafka Producer Instance for each Http Request每个 Http 请求的多个 Kafka 生产者实例
【发布时间】:2021-09-03 07:22:36
【问题描述】:

我有一个可以被多个用户同时调用的休息端点。这个休息端点调用事务性 Kafka 生产者。 我的理解是,如果我们使用 Transaction,我不能同时使用相同的 Kafka Producer 实例。

如何高效地为每个 HTTP 请求创建一个新的 Kafka 生产者实例?

//Kafka Transaction enabled
producerProps.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
producerProps.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "prod-1-" );

@Service
public class ProducerService {
    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    public void postMessage(final MyUser message) {
        // wrapping the send method in a transaction
        this.kafkaTemplate.executeInTransaction(kafkaTemplate -> {
              kafkaTemplate.send("custom", null, message);
        }

    }

【问题讨论】:

    标签: spring-boot apache-kafka spring-kafka kafka-producer-api


    【解决方案1】:

    请参阅 DefaultKafkaProducerFactory 的 javadocs。它为生产者发起的事务维护生产者缓存。

    /**
     * The {@link ProducerFactory} implementation for a {@code singleton} shared {@link Producer} instance.
     * <p>
     * This implementation will return the same {@link Producer} instance (if transactions are
     * not enabled) for the provided {@link Map} {@code configs} and optional {@link Serializer}
     * implementations on each {@link #createProducer()} invocation.
    
    ...
    
     * Setting {@link #setTransactionIdPrefix(String)} enables transactions; in which case, a
     * cache of producers is maintained; closing a producer returns it to the cache. The
     * producers are closed and the cache is cleared when the factory is destroyed, the
     * application context stopped, or the {@link #reset()} method is called.
    
    ...
    
     */
    

    【讨论】:

    • 罗素。万分感谢。所以我的理解是,我不需要为每个 Http 请求创建新的 Producer。即使 2 个 HTTP 请求同时尝试启动 Kafka 事务,DefaultKafkaProducerFactory 也会处理它。
    • 是的,这一切都由框架处理。与所有 Spring 项目一样,这使您可以专注于业务逻辑,而不是这些低级的细微差别。
    • 顺便说一句,如果你在每个事务中所做的只是发送一条消息,而没有做任何其他事情,那为什么还要使用事务呢?
    • 另外,对于生产者发起的事务,如果你有多个应用实例,事务id前缀在每个实例上必须是唯一的。
    • 阅读 javadocs。我在我的答案中复制了它。
    猜你喜欢
    • 2020-07-20
    • 2012-01-04
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2017-05-02
    • 2018-08-04
    相关资源
    最近更新 更多