JSCODE Logo
JSCODE 박재성JSCODE 제이온JSCODE 시니
온라인 강의프로그래밍 과외책/전자책무료 강의
유튜브블로그
후기
완강 후기 이벤트블로그 리뷰 이벤트AWS SAA 합격 후기 이벤트
회사명 : JSCODE대표 : 박재성사업자 등록번호 : 244-22-01557통신판매업 : 제 2023-인천미추홀-0381 호

서울특별시 구로구 경인로 20가길 11(오류동, 아델리아)

Copyright ⓒ 2026 JSCODE - 최상위 현업 개발자들의 프로그래밍 교육 All rights reserved.

이용약관개인정보처리방침

실전에서 바로 써먹는 Kafka 입문

Kafka 사전 지식 / 환경 셋팅

Kafka를 왜 배워야할까?
Kafka란? / 메시지 큐(Message Queue)란?
Kafka 설치할 환경 셋팅하기 (feat. EC2)
AWS EC2에 Kafka 설치/실행하기

Kafka 기본 개념

Kafka의 기본 구성 (Topic, Consumer, Producer)
토픽 생성하기 / 조회하기 / 삭제하기
Kafka에 메시지 넣기 / Kafka에서 메시지 조회하기
메시지를 어디까지 읽었는 지 기억하고, 그 다음 메시지부터 처리하기 (Consumer Group, Offset)
[보충 자료] 토픽, 컨슈머 그룹 이름 짓는 법 (Naming Convention)
[실습] Spring Boot에 Kafka 연결을 위한 코드 추가하기
[실습] Spring Boot로 Kafka에 메시지 넣는 코드 작성하기 (Producer)
[실습] Spring Boot가 Kafka에 메시지 잘 넣는 지 테스트해보기
[실습] Spring Boot로 Kafka에서 메시지 조회하기 (Consumer)
Kafka의 비동기 처리로 인한 성능 이점 느껴보기

Kafka 메시지 처리 실패 시 대처 방법

[실습] Spring Boot로 Kafka에서 처리에 실패한 메시지를 재시도(Retry)하도록 만들기
[실습] Spring Boot로 Kafka에서 재시도조차 실패한 메시지를 따로 보관하기 (DLT, Dead Letter Topic)
[실습] Spring Boot로 재시도조차 실패한 메시지 사후 처리하기

Kafka 메시지 처리 성능 높이기 (병렬 처리)

컨슈머가 메시지를 하나씩만 처리하는 현상
파티션(Partition)이란? / 특징
[실습] Spring Boot로 하나의 파티션에는 정말 하나의 컨슈머만 할당되는 지 확인해보기
특정 토픽의 파티션 수 조회하기 / 설정하기 / 변경하기
[실습] Spring Boot로 여러 개의 파티션에 메시지가 골고루 들어가는 지 확인해보기
[실습] Spring Boot에서 여러 개의 컨슈머로 메시지 병렬적으로 처리하기
[실습] Spring Boot에서 하나의 컨슈머로 메시지 병렬적으로 처리하기
적정 파티션 개수 계산하는 방법
컨슈머가 메시지를 지연 없이 잘 처리하고 있는 지 확인하는 방법 (Consumer Lag)

Kafka 장애 대비하기 (고가용성)

노드(node), 브로커(broker), 컨트롤러(controller), 클러스터(cluster), 레플리케이션(replication)이란?
[실습] kafka 서버 총 3대 셋팅하기
[실습] Kafka 서버 3대가 서로 잘 연동됐는 지 확인하기
토픽 세부 정보 출력값 정보 해석하기 (Isr, Leader, Replicas 등)
[실습] 팔로워 파티션에 메시지를 넣으면 어떻게 될까?
[실습] 리더 파티션에 장애가 발생하면 어떻게 될까? / Kafka 서버 1대가 고장나면 어떻게 될까?
Kafka 서버는 몇 대를 운용하는 게 좋을까?
Spring Boot에 Kafka 서버 3대를 연결해서 사용하는 방법

[프로젝트] MSA 프로젝트에서 Kafka 도입하기

프로젝트 설계
[실습] Spring Boot로 UserService 서버 초기 환경 설정하기
[실습] 회원가입 API 전체 뼈대 만들기
[실습] 회원 가입 비즈니스 로직 짜기
[실습] Spring Boot로 EmailService 서버 초기 환경 설정하기
[실습] 이메일 발송을 처리할 Consumer 로직 짜기
[실습] 프로젝트 구조에 맞게 Kafka 셋팅하기
[실습] 잘 작동하는 지 테스트해보기
← 블로그 목록으로 돌아가기

[실습] 이메일 발송을 처리할 Consumer 로직 짜기

JSCODE 박재성
JSCODE 박재성
2026. 03. 13.
author
JSCODE 박재성
category
Kafka
createdAt
Dec 6, 2025 05:15 AM
isPublic
isPublic
series
실전에서 바로 써먹는 Kafka 입문
slug
practice-email-consumer-logic
type
post
updatedAt
Mar 13, 2026 09:00

✅ 이메일 발송을 처리할 Consumer 로직 짜기

  1. Kafka의 메시지를 가져와 담을 객체 만들기
    1. UserSignedUpEvent
      public class UserSignedUpEvent { private Long userId; private String email; private String name; // 역직렬화(String 형태의 카프카 메시지 -> Java 객체)시 필요함 public UserSignedUpEvent() { } public UserSignedUpEvent(Long userId, String email, String name) { this.userId = userId; this.email = email; this.name = name; } public static UserSignedUpEvent fromJson(String json) { try { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, UserSignedUpEvent.class); } catch (JsonProcessingException e) { throw new RuntimeException("JSON 파싱 실패"); } } public Long getUserId() { return userId; } public String getEmail() { return email; } public String getName() { return name; } }
       
  1. Consumer 로직 작성하기
    1. UserSignedUpEventConsumer
      @Service public class UserSignedUpEventConsumer { @KafkaListener( topics = "user.signed-up", groupId = "email-service", concurrency = "3" ) @RetryableTopic( attempts = "5", backoff = @Backoff(delay = 1000, multiplier = 2), dltTopicSuffix = ".dlt" ) public void consume(String message) throws InterruptedException { UserSignedUpEvent userSignedUpEvent = UserSignedUpEvent.fromJson(message); // 실제 이메일 발송 로직은 생략 String receiverEmail = userSignedUpEvent.getEmail(); String subject = userSignedUpEvent.getName() + "님, 회원 가입을 축하드립니다!"; Thread.sleep(3000); // 이메일 발송에 3초 정도 시간이 걸리는 걸 가정 System.out.println("이메일 발송 완료"); } }
      위 로직에서 추가로 이메일 발송 로그를 DB에 저장하는 로직을 추가해야 한다. 이 로직을 추가하기 위해 필요한 엔티티와 레포지토리를 생성해주자.
       
  1. 이메일 발송 로그를 남기기 위한 엔티티, 레포지토리 생성하기
    1. EmailLog
      @Entity @Table(name = "email_logs") public class EmailLog { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private Long receiverUserId; private String receiverEmail; private String subject; public EmailLog() { } public EmailLog(Long receiverUserId, String receiverEmail, String subject) { this.receiverUserId = receiverUserId; this.receiverEmail = receiverEmail; this.subject = subject; } // getter 메서드 }
EmailLogRepository
public interface EmailLogRepository extends JpaRepository<EmailLog, Long> { }
 
  1. Consumer 로직 보완하기
    1. 이메일 발송 로그를 DB에 저장하는 로직을 추가하자.
      UserSignedUpEventConsumer
      @Service public class UserSignedUpEventConsumer { private EmailLogRepository emailLogRepository; public UserSignedUpEventConsumer(EmailLogRepository emailLogRepository) { this.emailLogRepository = emailLogRepository; } @KafkaListener( topics = "user.signed-up", groupId = "email-service", concurrency = "3" ) @RetryableTopic( attempts = "5", backoff = @Backoff(delay = 1000, multiplier = 2), dltTopicSuffix = ".dlt" ) public void consume(String message) throws InterruptedException { UserSignedUpEvent userSignedUpEvent = UserSignedUpEvent.fromJson(message); String receiverEmail = userSignedUpEvent.getEmail(); String subject = userSignedUpEvent.getName() + "님, 회원 가입을 축하드립니다!"; Thread.sleep(3000); System.out.println("이메일 발송 완료"); EmailLog emailLog = new EmailLog( userSignedUpEvent.getUserId(), receiverEmail, subject ); emailLogRepository.save(emailLog); } }
       
  1. DLT로 빠지는 메시지 처리하는 로직 추가하기
    1. UserSignedUpEventDltConsumer
      @Service public class UserSignedUpEventDltConsumer { @KafkaListener( topics = "user.signed-up.dlt", groupId = "email-service" ) public void consume(String message) { // 실제 로직은 생략 System.out.println("로그 시스템에 전송 : " + message); System.out.println("Slack에 알림 발송"); } }
 
 
 

✅ 중간 체크

전체 프로젝트 구조에서 EamilService에 해당하는 부분을 다 구현했다. 다음 강의에서는 마지막으로 Kafka가 잘 작동하도록 셋팅해주자.
notion image
📎
이 글은 실전에서 바로 써먹는 Kafka 입문 강의의 수업 자료 중 일부입니다.