Spring Kafka making a producer

Viewed 23

I have to make a KafkaProducer to use inside my Service. I write this code, but I'm not sure about the structure and the good working.

@Configuration
public class KafkaConfiguration {

    @Value("${spring.kafka.server-config}")
    private String serverConfig;

    @Bean
    public Producer<String, String> producer() {
        Map<String, Object> configs = new HashMap<>();

        configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, serverConfig);
        configs.put(ProducerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString());

        return new KafkaProducer<>(configs, new StringSerializer(), new StringSerializer());
    }
}

And the Service that use the Configuration is

@Service
public class kafkaService {

    @Autowired
    private KafkaConfiguration kafkaConfiguration;

    @Value("${spring.kafka.topic}")
    private String topic;

    public void notify(String msg) throws Exception {
        kafkaConfiguration.producer().send(new ProducerRecord<>(this.topic, msg)).get();
    }

}

Can I make an @Autowired of a Configuration bean? I can't use kafka.core, but there are better ways to create a producer and use send method on producer.

Thanks for help

1 Answers
Related