简体   繁体   中英

Creating a message driven inbound channel adapter to connect to Kafka using Spring integration java configuration

Java代码使用Spring Integration Java DSL创建Kafka使用者

Use the below code to create a message driven adapter to connect to consume message from kafka

@Value("${spring.kafka.bootstrap-servers}")
private String bootstrapServers;
@Value("${spring.kafka.topic}")
private String springIntegrationKafkaTopic;
@Bean
public IntegrationFlow kafkaReader() throws Exception {

    return IntegrationFlows
            .from(Kafka.messageDrivenChannelAdapter(listener(),ListenerMode.record))
            .channel("queureader")
            .get();
}

@Bean
public KafkaMessageListenerContainer listener() {
    return new KafkaMessageListenerContainer(consumerFactory(), new ContainerProperties(this.springIntegrationKafkaTopic));
}

@Bean
public ConsumerFactory consumerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.bootstrapServers);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "kafkaListener");
    return new DefaultKafkaConsumerFactory(props);
}


@ServiceActivator(inputChannel = "queureader")
public void Print(Message<?> msg)  {

    System.out.println(msg.getPayload().toString());
}

In application.properties

  • spring.kafka.bootstrap-servers = We need to mention the server name -spring.kafka.topic= Name of the topic

You can mention any value for ConsumerConfig.GROUP_ID_CONFIG.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM