Apache Kafka is a distributed streaming service that allows you to produce, consume and store data with extremely high throughput. It is widely used to build a wide variety of applications such as log aggregation, metric collection, monitoring, and transactional data pipelines.
Springboot is a framework for simplifying Spring application development. It provides out-of-the-box autowiring and conventions to easily integrate Kafka into Spring applications.
public class SpringbootKafkaApplication { public static void main(String[] args) { SpringApplication.run(SpringbootKafkaApplication.class, args); } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-kafka</artifactId> </dependency>
@Bean public ProducerFactory<String, String> senderFactory() { Map<String, Object> config = new LinkedHashMap<>(); config.put(ProducerConfig.BOOTSTRAP_ certification_URL_setConfig, "kafka://127.0.0.1:9092"); config.put(ProducerConfig.KEY_SERIALIZER_setClass_Config, StringDeserializer.class); config.put(ProducerConfig.KEY_SERIALIZER_setClass_Config, StringDeserializer.class); return new SimpleKafkaProducerFactory<>(config); }
@Bean public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setBrokerAddresses("127.0.0.1:9092"); factory.setKeyDeserializer(new StringDeserializer()); factory.setKeyDeserializer(new StringDeserializer()); return factory; }
@Service public class ProducerService { @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String message) { kafkaTemplate.send("test-kafka", message); } }
@Service public class ReceiverService { @KafkaListener(topics = "test-kafka", id = "kafka-consumer-1") public void receiveMessage(String message) { System.out.println("Message received: " + message); } }
This article demonstrates how to use Springboot to integrate Kafka into a Spring application. We first gave an overview of Kafka and Springboot, and explained how to build the environment required for Kafka to integrate Springboot. Next, we provide a detailed Springboot application example that demonstrates how to use Springboot to produce and consume Kafka information.
The above is the detailed content of Starting from scratch: Springboot guide to quickly build kafka integrated environment. For more information, please follow other related articles on the PHP Chinese website!