使用Spring Integration Java配置创建消息驱动的入站通道适配器以连接到Kafka

时间:2018-08-01 11:16:09

标签: java spring-integration spring-integration-dsl

使用Spring Integration Java DSL创建Java消费者的Java代码

1 个答案:

答案 0 :(得分:1)

使用以下代码创建消息驱动的适配器,以连接以使用来自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());
}

在application.properties中

  • spring.kafka.bootstrap-servers =我们需要提及服务器名称 -spring.kafka.topic =主题名称

您可以提及ConsumerConfig.GROUP_ID_CONFIG的任何值。