Apache Kafka 支持
通过提供 spring-kafka 项目的自动配置来支持 Apache Kafka。
Kafka 配置由 spring.kafka.* 中的外部配置属性控制。
例如,你可以在 application.properties 中声明以下部分:
-
Properties
-
YAML
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup
spring:
kafka:
bootstrap-servers: "localhost:9092"
consumer:
group-id: "myGroup"
提示:要在启动时创建主题,添加一个类型为 NewTopic 的 bean。
如果主题已存在,则忽略该 bean。
有关更多支持的选项,请参阅 KafkaProperties。
发送消息
Spring 的 KafkaTemplate 是自动配置的,你可以直接将其自动装配到你自己的 bean 中,如下例所示:
-
Java
-
Kotlin
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final KafkaTemplate<String, String> kafkaTemplate;
public MyBean(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
// ...
public void someMethod() {
this.kafkaTemplate.send("someTopic", "Hello");
}
}
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Component
@Component
class MyBean(private val kafkaTemplate: KafkaTemplate<String, String>) {
// ...
fun someMethod() {
kafkaTemplate.send("someTopic", "Hello")
}
}
注意:如果定义了 spring.kafka.producer.transaction-id-prefix 属性,则会自动配置 KafkaTransactionManager。
此外,如果定义了 RecordMessageConverter bean,它会自动关联到自动配置的 KafkaTemplate。
接收消息
当 Apache Kafka 基础设施存在时,任何 bean 都可以用 @KafkaListener 注解来创建监听器端点。
如果没有定义 KafkaListenerContainerFactory,则会使用 spring.kafka.listener.* 中定义的键自动配置一个默认的工厂。
以下组件在 someTopic 主题上创建监听器端点:
-
Java
-
Kotlin
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@KafkaListener(topics = "someTopic")
public void processMessage(String content) {
// ...
}
}
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.stereotype.Component
@Component
class MyBean {
@KafkaListener(topics = ["someTopic"])
fun processMessage(content: String?) {
// ...
}
}
如果定义了 KafkaTransactionManager bean,它会自动关联到容器工厂。
同样,如果定义了 RecordFilterStrategy、CommonErrorHandler、AfterRollbackProcessor 或 ConsumerAwareRebalanceListener bean,它们会自动关联到默认工厂。
根据监听器类型,RecordMessageConverter 或 BatchMessageConverter bean 会关联到默认工厂。
如果对于批处理监听器只存在 RecordMessageConverter bean,它会被包装在 BatchMessageConverter 中。
提示:自定义的 ChainedKafkaTransactionManager 必须标记为 @Primary,因为它通常引用自动配置的 KafkaTransactionManager bean。
Kafka Streams
Spring for Apache Kafka 提供了一个工厂 bean 来创建 StreamsBuilder 对象并管理其流的生命周期。
只要 kafka-streams 在类路径上且通过 @EnableKafkaStreams 注解启用了 Kafka Streams,Spring Boot 就会自动配置所需的 KafkaStreamsConfiguration bean。
启用 Kafka Streams 意味着必须设置应用程序 ID 和引导服务器。
前者可以使用 spring.kafka.streams.application-id 配置,如果未设置则默认为 spring.application.name。
后者可以全局设置或仅针对流进行特定覆盖。
使用专用属性可以使用几个额外的属性;其他任意 Kafka 属性可以使用 spring.kafka.streams.properties 命名空间设置。
有关更多信息,请参阅 额外的 Kafka 属性。
要使用工厂 bean,将 StreamsBuilder 装配到你的 @Bean 中,如下例所示:
-
Java
-
Kotlin
import java.util.Locale;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Produced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafkaStreams;
import org.springframework.kafka.support.serializer.JsonSerde;
@Configuration(proxyBeanMethods = false)
@EnableKafkaStreams
public class MyKafkaStreamsConfiguration {
@Bean
public KStream<Integer, String> kStream(StreamsBuilder streamsBuilder) {
KStream<Integer, String> stream = streamsBuilder.stream("ks1In");
stream.map(this::uppercaseValue).to("ks1Out", Produced.with(Serdes.Integer(), new JsonSerde<>()));
return stream;
}
private KeyValue<Integer, String> uppercaseValue(Integer key, String value) {
return new KeyValue<>(key, value.toUpperCase(Locale.getDefault()));
}
}
import org.apache.kafka.common.serialization.Serdes
import org.apache.kafka.streams.KeyValue
import org.apache.kafka.streams.StreamsBuilder
import org.apache.kafka.streams.kstream.KStream
import org.apache.kafka.streams.kstream.Produced
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.kafka.annotation.EnableKafkaStreams
import org.springframework.kafka.support.serializer.JsonSerde
@Configuration(proxyBeanMethods = false)
@EnableKafkaStreams
class MyKafkaStreamsConfiguration {
@Bean
fun kStream(streamsBuilder: StreamsBuilder): KStream<Int, String> {
val stream = streamsBuilder.stream<Int, String>("ks1In")
stream.map(this::uppercaseValue).to("ks1Out", Produced.with(Serdes.Integer(), JsonSerde()))
return stream
}
private fun uppercaseValue(key: Int, value: String): KeyValue<Int?, String?> {
return KeyValue(key, value.uppercase())
}
}
默认情况下,StreamsBuilder 对象管理的流会自动启动。
你可以使用 spring.kafka.streams.auto-startup 属性来自定义此行为。
额外的 Kafka 属性
自动配置支持的属性显示在附录的 集成属性 部分。 请注意,在大多数情况下,这些属性(连字符或驼峰式)直接映射到 Apache Kafka 的点分隔属性。 有关详细信息,请参阅 Apache Kafka 文档。
名称中不包含客户端类型(producer、consumer、admin 或 streams)的属性被视为通用属性,适用于所有客户端。
如果需要,这些通用属性中的大多数都可以为一个或多个客户端类型覆盖。
Apache Kafka 将属性的重要性指定为 HIGH、MEDIUM 或 LOW。 Spring Boot 自动配置支持所有 HIGH 重要性属性、一些选定的 MEDIUM 和 LOW 属性,以及任何没有默认值的属性。
只有 Kafka 支持的属性的一部分可以通过 KafkaProperties 类直接使用。
如果你希望使用不直接支持的额外属性来配置各个客户端类型,请使用以下属性:
-
Properties
-
YAML
spring.kafka.properties[prop.one]=first
spring.kafka.admin.properties[prop.two]=second
spring.kafka.consumer.properties[prop.three]=third
spring.kafka.producer.properties[prop.four]=fourth
spring.kafka.streams.properties[prop.five]=fifth
spring:
kafka:
properties:
"[prop.one]": "first"
admin:
properties:
"[prop.two]": "second"
consumer:
properties:
"[prop.three]": "third"
producer:
properties:
"[prop.four]": "fourth"
streams:
properties:
"[prop.five]": "fifth"
这将通用 Kafka 属性 prop.one 设置为 first(适用于生产者、消费者、管理员和流),将管理员属性 prop.two 设置为 second,将消费者属性 prop.three 设置为 third,将生产者属性 prop.four 设置为 fourth,将流属性 prop.five 设置为 fifth。
你还可以按如下方式配置 Spring Kafka JsonDeserializer:
-
Properties
-
YAML
spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties[spring.json.value.default.type]=com.example.Invoice
spring.kafka.consumer.properties[spring.json.trusted.packages]=com.example.main,com.example.another
spring:
kafka:
consumer:
value-deserializer: "org.springframework.kafka.support.serializer.JsonDeserializer"
properties:
"[spring.json.value.default.type]": "com.example.Invoice"
"[spring.json.trusted.packages]": "com.example.main,com.example.another"
同样,你可以禁用 JsonSerializer 在头中发送类型信息的默认行为:
-
Properties
-
YAML
spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer
spring.kafka.producer.properties[spring.json.add.type.headers]=false
spring:
kafka:
producer:
value-serializer: "org.springframework.kafka.support.serializer.JsonSerializer"
properties:
"[spring.json.add.type.headers]": false
重要:以这种方式设置的属性会覆盖 Spring Boot 明确支持的任何配置项。
使用嵌入式 Kafka 进行测试
Spring for Apache Kafka 提供了一种使用嵌入式 Apache Kafka broker 测试项目的便捷方法。
要使用此功能,请使用 spring-kafka-test 模块中的 @EmbeddedKafka 注解测试类。
有关更多信息,请参阅 Spring for Apache Kafka 参考手册。
要使 Spring Boot 自动配置与上述嵌入式 Apache Kafka broker 一起工作,你需要将嵌入式 broker 地址的系统属性(由 EmbeddedKafkaBroker 填充)重新映射到 Apache Kafka 的 Spring Boot 配置属性。
有几种方法可以做到这一点:
-
在测试类中提供系统属性,将嵌入式 broker 地址映射到
spring.kafka.bootstrap-servers:
-
Java
-
Kotlin
static {
System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY, "spring.kafka.bootstrap-servers");
}
init {
System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY, "spring.kafka.bootstrap-servers")
}
-
在
@EmbeddedKafka注解上配置属性名称:
-
Java
-
Kotlin
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.test.context.EmbeddedKafka;
@SpringBootTest
@EmbeddedKafka(topics = "someTopic", bootstrapServersProperty = "spring.kafka.bootstrap-servers")
class MyTest {
// ...
}
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.kafka.test.context.EmbeddedKafka
@SpringBootTest
@EmbeddedKafka(topics = ["someTopic"], bootstrapServersProperty = "spring.kafka.bootstrap-servers")
class MyTest {
// ...
}
-
在配置属性中使用占位符:
-
Properties
-
YAML
spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}
spring:
kafka:
bootstrap-servers: "${spring.embedded.kafka.brokers}"