깃헙에 있는 정리본은 참고해주세요!
https://github.com/namusik/TIL-SampleProject/tree/main/Kafka
https://github.com/namusik/TIL-SampleProject/tree/main/Kafka/Sample%20Project
IntelliJ
Spring-boot
java 11
gradle
spring web
spring for Apache Kafka
!!Producer/Consumer 설정을 bean을 통해서도 가능. 설정을 여러개로 하고 싶다면 bean 사용
spring:
kafka:
consumer:
bootstrap-servers: localhost:9092
group-id: treesick
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
producer:
bootstrap-servers: localhost:9092
key-serializer: org.apache.kafka.common.serialization.StringDeserializer
value-serializer: org.apache.kafka.common.serialization.StringDeserializer
import lombok.RequiredArgsConstructor;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class KafakaProducerService {
private static final String TOPIC = "treesick";
private final KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String message) {
System.out.println("produce message = " + message);
kafkaTemplate.send(TOPIC, message);
}
}
프로듀서 서비스클래스
kafkaTemplate.send를 통해 kafka 서버로 토픽과 메시지를 보냄.
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class KafkaConsumerService {
@KafkaListener(topics = "treesick", groupId = "namu")
public void consume(String message) throws IOException {
System.out.println("consume message = " + message);
}
}
Consumer 서비스클래스
@KafkaListener 어노테이션을 달아서 토픽과 컨슈머그룹아이디 정보를 써줌
메시지가 도달하면 출력을 하도록 코딩
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sample.kafka.service.KafkaProducerService;
@RestController
@RequiredArgsConstructor
public class KafkaController {
private final KafkaProducerService producerService;
@PostMapping("/kafka")
public String sendMessage(@RequestParam("message") String message) {
producerService.sendMessage(message);
return "success";
}
}
kafka에 메시지를 전달할 수 있도록 restApi를 만들어 주기
Postman을 사용해서 api를 실행시키면
성공시 "success"를 반환하고
인텔리제이에는 컨슈머가 받은 메시지인 "hello"를 출력해주면 성공
이번 연습예제에서는 String 형태의 메시지를 주고 받는 연습을 했는데 보통의 프로젝트에서는 JSON형태의 객체를 주고 받을테니 다음에는 JSON메시지를 주고받는 예제를 만들어 보겠습니다~!
https://victorydntmd.tistory.com/348
https://oingdaddy.tistory.com/308