我可以在单例范围内使用 KafkaTemplate 吗?
Can I use KafkaTemplate with singleton scope?
在 spring 上下文中将 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);
}
}
}
问题与 class 名称 KafkaTemplate 有关。
在我看来,每个请求都应该有一个新实例。
为什么您认为每个请求都需要一个新实例?通常您只需要一个实例 - 事实上,即使您使用多个实例,也会使用相同的底层 Kafka Producer
(默认情况下)。
在 spring 上下文中将 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);
}
}
}
问题与 class 名称 KafkaTemplate 有关。 在我看来,每个请求都应该有一个新实例。
为什么您认为每个请求都需要一个新实例?通常您只需要一个实例 - 事实上,即使您使用多个实例,也会使用相同的底层 Kafka Producer
(默认情况下)。