首页 > 解决方案 > 我可以将 KafkaTemplate 与单例范围一起使用吗?

问题描述

org.springframework.kafka.core.KafkaTemplate在弹簧上下文中作为单例连接是正确的方法,还是我可以使用原型范围?

单例示例:

@Slf4j
@RequiredArgsConstructor
@Service
public class IntegrationService {
    private final KafkaTemplate kafkaTemplate;

    public void sendToConsumerService(Dto dto) {
        AvroDto avroDto = convertToAvro(dto);
        try {
            ListenableFuture<SendResult<Object, GenericRecord>> sendResultListenableFuture
                    = kafkaTemplate.send("consumer-topic",
                    TopicKeys.getTopicKey("consumer-topic", avroDto),
                    avroDto);
            if (sendResultListenableFuture.isDone()) {
                log.debug("Sent message to Kafka: {}", avroDto)
            }
        } catch (Exception ex) {
            log.warn("Error sending message to Kafka", ex);
        }
    }
}

该问题与类名KafkaTemplate有关。在我看来,每个请求都应该有一个新实例。

标签: springspring-bootspring-kafka

解决方案


为什么您认为每个请求都需要一个新实例?通常你只需要一个实例——事实上,即使你使用多个实例,也会使用相同的底层 Kafka Producer(默认情况下)。


推荐阅读