Prerequisites: You must install and run Apache Kafka.
Then you must put the Spring for Apache Kafka (spring-kafka
) JAR and all of its dependencies on your class path.
The easiest way to do that is to declare a dependency in your build tool.
If you are not using Spring Boot, declare the spring-kafka
jar as a dependency in your project.
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>{project-version}</version>
</dependency>
compile 'org.springframework.kafka:spring-kafka:{project-version}'
Important
|
When using Spring Boot, (and you haven’t used start.spring.io to create your project), omit the version and Boot will automatically bring in the correct version that is compatible with your Boot version: |
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
compile 'org.springframework.kafka:spring-kafka'
However, the quickest way to get started is to use start.spring.io (or the wizards in Spring Tool Suits and Intellij IDEA) and create a project, selecting 'Spring for Apache Kafka' as a dependency.
This quick tour works with the following versions:
-
Apache Kafka Clients 3.0.0
-
Spring Framework 5.3.x
-
Minimum Java version: 8
The simplest way to get started is to use start.spring.io (or the wizards in Spring Tool Suits and Intellij IDEA) and create a project, selecting 'Spring for Apache Kafka' as a dependency. Refer to the Spring Boot documentation for more information about its opinionated auto configuration of the infrastructure beans.
Here is a minimal consumer application.
link:{java-examples}/started/consumer/Application.java[role=include]
link:{kotlin-examples}/started/consumer/Application.kt[role=include]
spring.kafka.consumer.auto-offset-reset=earliest
The NewTopic
bean causes the topic to be created on the broker; it is not needed if the topic already exists.
link:{java-examples}/started/producer/Application.java[role=include]
link:{kotlin-examples}/started/producer/Application.kt[role=include]
Important
|
Spring for Apache Kafka is designed to be used in a Spring Application Context.
For example, if you create the listener container yourself outside of a Spring context, not all functions will work unless you satisfy all of the …Aware interfaces that the container implements.
|
Here is an example of an application that does not use Spring Boot; it has both a Consumer
and Producer
.
link:{java-examples}/started/noboot/Sender.java[role=include]
link:{java-examples}/started/noboot/Listener.java[role=include]
link:{java-examples}/started/noboot/Config.java[role=include]
link:{kotlin-examples}/started/noboot/Sender.kt[role=include]
link:{kotlin-examples}/started/noboot/Listener.kt[role=include]
link:{kotlin-examples}/started/noboot/Config.kt[role=include]
As you can see, you have to define several infrastructure beans when not using Spring Boot.