这是我们的方法。以下是两个示例类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {
@Autowired
protected KafkaConsumerProperties kafkaConsumerProperties;
@Bean
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
}
...
@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();
@ConfigurationProperties("kafkaConsumerConfig")
public Map<String, Object> getKafkaConsumerConfig() {
return (kafkaConsumerConfig);
}
...
要从属性文件提供kafkaConsumer配置,可以使用:mapname [key] = value
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer
要从yaml文件提供kafkaConsumer配置,可以使用“ [key]”:value在application.yml文件中:
kafkaConsumerConfig:
"[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
"[group.id]": test-consumer-group-local
"[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
"[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer