-
Kafka Producer 커스터마이징하기 #2Kafka 2024. 5. 11. 06:16반응형
다중 인터페이스를 정의하는 경우
https://sillydev.tistory.com/72
이전 글을 통해 Kafka Producer Bean 을 주입하는 방법에 대해 정리했다. 그런데 전송하고자 하는 Broker가 여러 개인 경우는 어떻게 할까? 다를게 없이 Bean을 여러 번 주입하면 된다.
@Configuration public class KafkaProducerConfig { @Bean public void init() { // Producer 관련 설정을 이미 세팅했다고 가정 List<Map<String, Object>> list = getProducerConfigs(); for (Map config : list) { ProducerFactory<String, String> factory = new DefaultKafkaProducerFactory<>(config); KafkaTemplate<String, String> kafkaTemplate = new KafkaTemplate<>(factory); // Spring 동적 Bean 주입 ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext(); ConfigurableListableBeanFactory beanFactory = (ConfigurableListableBeanFactory) ((GenericApplicationContext) applicationContext).getBeanFactory(); beanFactory.registerSingleton((String) config.get("id"), kafkaTemplate); } } }
사용할 때는 등록했던 Bean의 id로 가져와서 똑같이 전송할 수 있다.@RestController public class ProducerController { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @PostMapping("/send") public String sendMsg(@RequestParam String topic, @RequestParam String message) { KafkaTemplate<String, String> kafkaTemplate = ApplicationContextProvider.getApplicationContext().getBean("id"); kafkaTemplate.send(topic, message); // SendResult<byte[],byte[]> result = kafkaTemplate.send(producerRecord).get(); 처럼 전송 결과 응답 받을 수 있다. return "Message sent to Kafka topic: " + topic; } }
반응형'Kafka' 카테고리의 다른 글
Kafka Producer 커스터마이징하기 #1 (0) 2024.05.11