JSCODE Logo
프로그래밍 과외블로그후기멘토진
회사명 : JSCODE대표 : 박재성사업자 등록번호 : 244-22-01557통신판매업 : 제 2023-인천미추홀-0381 호
학원 명칭 : 제이에스코드(JSCODE)원격학원학원설립ㆍ운영 등록번호 : 제6063호

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

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

이용약관개인정보처리방침
← 블로그 목록으로 돌아가기

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

JSCODE 박재성
JSCODE 박재성
2025-12-06
author
JSCODE 박재성
category
Kafka
createdAt
Dec 6, 2025
series
실전에서 바로 써먹는 Kafka 입문
slug
practice-email-consumer-logic
type
post
updatedAt
Dec 6, 2025 05:39 AM

✅ 이메일 발송을 처리할 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
author
JSCODE 박재성
category
Kafka
createdAt
Dec 6, 2025
series
실전에서 바로 써먹는 Kafka 입문
slug
type
series-footer
updatedAt
Dec 6, 2025 05:39 AM
📎
이 글은 실전에서 바로 써먹는 Elasticsearch 입문 (검색 최적화편) 강의의 수업 자료 중 일부입니다.