Apache Kafka 支援
Apache Kafka 透過提供 spring-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 和 bootstrap servers。應用 ID 可以使用 spring.kafka.streams.application-id
進行配置,如果未設定則預設為 spring.application.name
。bootstrap servers 可以全域性設定,也可以僅針對 Streams 特別覆蓋。
可以使用專用屬性設定幾個附加屬性;其他任意 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
(適用於生產者、消費者、admin 和 streams),admin 屬性 prop.two
設定為 second
,consumer 屬性 prop.three
設定為 third
,producer 屬性 prop.four
設定為 fourth
,streams 屬性 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 代理進行專案測試。要使用此功能,請使用 spring-kafka-test
模組中的 @EmbeddedKafka
註解標註測試類。更多資訊請參閱 Spring for Apache Kafka 的參考手冊。
為了使 Spring Boot 自動配置與上述嵌入式 Apache Kafka 代理一起工作,您需要將嵌入式代理地址的系統屬性(由 EmbeddedKafkaBroker
填充)重新對映到 Spring Boot 中 Apache Kafka 的配置屬性。有幾種方法可以做到這一點
-
在測試類中提供系統屬性,將嵌入式代理地址對映到
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}"