Skip to content

Apache Kafka

thing-zoo edited this page Aug 7, 2023 · 2 revisions

참고자료

  • 위 블로그는 docker-compose.yml만 참고하자
Simple Example Step 1:

Add Kafka Dependencies Open your project's build.gradle and add the Spring Kafka dependency:

Gradle:

implementation 'org.springframework.kafka:spring-kafka'

Step 2: Configure Kafka in application.properties In the src/main/resources/application.properties file, add the following Kafka configurations:

# Kafka configuration
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-group-id

Step 3: Create a Kafka Producer Create a Kafka producer to send messages to a Kafka topic. For this example, let's assume we want to send messages to a topic named "test-topic".

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
    
@Service
public class KafkaProducerService {
    private static final String TOPIC_NAME = "test-topic";
    
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    
    public void sendMessage(String message) {
        kafkaTemplate.send(TOPIC_NAME, message);
        System.out.println("Sent message: " + message);
    }
}
    

Step 4: Create a Kafka Consumer Create a Kafka consumer to receive messages from the "test-topic" topic.

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
    
@Service
public class KafkaConsumerService {
    @KafkaListener(topics = "test-topic", groupId = "my-group-id")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}
    

Step 5: Testing the Kafka Integration Now, you can test the Kafka integration by sending and receiving messages. You can use any controller or service in your application to interact with the Kafka producer and consumer.

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
    
@RestController
public class KafkaController {
    private final KafkaProducerService producerService;
    
    public KafkaController(KafkaProducerService producerService) {
        this.producerService = producerService;
    }
    
    @PostMapping("/send")
    public void sendMessage(@RequestBody String message) {
        producerService.sendMessage(message);
    }
}
    

With the above controller, you can send messages to Kafka by making a POST request to /send with a message body.

Clone this wiki locally