spring - 我可以将 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有关。在我看来,每个请求都应该有一个新实例。
解决方案
为什么您认为每个请求都需要一个新实例?通常你只需要一个实例——事实上,即使你使用多个实例,也会使用相同的底层 Kafka Producer
(默认情况下)。
推荐阅读
- python - 如何在特定的父 div 类中定位特定的 div 类,python selenium
- ag-grid - 如何为 AgGrid 标题组设置自定义样式(不是类)?
- python - 如何在python中的多个数据框中添加新列
- java - 从 dot net core 调用 Java 组件
- java - 使用 ASM 动态检测 java 类时出现“LinkageError:尝试重复的类定义”
- nginx - 在 nginx 中将非 Cloudfront 请求重定向到 Cloudfront 的最佳实践
- angular - 如何在 environment.prod.ts 和 environment.ts (Angular) 中正确添加基本 url?
- python - 如何通过 AWS Wrangler 使用 SSL 验证
- javascript - Google 脚本 (.gs) 返回重复的行
- php - php_network_getaddresses: getaddrinfo failed: No such host is known,为什么会这样显示