260715_03_ENH: 이메일 대량 발송 스케쥴러로 분리

This commit is contained in:
2026-07-15 10:22:35 +09:00
parent 132a8a0367
commit 791d01c6fc
5 changed files with 210 additions and 4 deletions

View File

@@ -19,7 +19,8 @@ public final class NotihubConst {
public static final List<Short> KKO_TYPE_CODE_LIST = List.of(SendType.KKO_AT.getCode());
public static final List<Short> EMAIL_TYPE_CODE_LIST = List.of(SendType.EMAIL.getCode());
public static final String EMAIL_RESERVATION_PREFIX = "RESERVATION_";
public static final short EMAIL_STANDBY = 100;
public static final short EMAIL_STANDBY = 100; // 발송 전 대기
public static final short EMAIL_SENDING = 101; // worker 점유/발송 시도 중
public static final short EMAIL_PENDING = (short) 111; // 발송요청은 성공했으나 json_return 미조회
public static final short EMAIL_SEND_FAIL = (short) 109; // 발송요청 실패(또는 return_key 미수신)
public static final short EMAIL_NOT_RESULT = (short) 119; // json_return 조회 실패/결과없음(최종상태 확보 실패)

View File

@@ -8,8 +8,10 @@ import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface SendRepository extends JpaRepository<TSendEntity, Long> {
@@ -55,6 +57,55 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
Pageable pageable
);
@Query("""
select s
from TSendEntity s
where s.sendTy = :sendTy
and s.resultCode = :resultCode
and s.resve = false
and s.bulkSendKey is not null
and s.sendDt <= :now
order by s.sendIdx asc
""")
List<TSendEntity> findBulkStandbySendEmail(
short sendTy,
short resultCode,
LocalDateTime now,
Pageable pageable
);
@Transactional
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update TSendEntity s
set s.resultCode = :sendingResultCode
where s.sendIdx = :sendIdx
and s.resultCode = :standbyResultCode
""")
int markEmailSending(
Long sendIdx,
short standbyResultCode,
short sendingResultCode
);
@Transactional
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update TSendEntity s
set s.resultCode = :standbyResultCode
where s.sendTy = :sendTy
and s.resultCode = :sendingResultCode
and s.resve = false
and s.bulkSendKey is not null
and s.sendDt <= :staleBefore
""")
int recoverStaleBulkEmailSending(
short sendTy,
short sendingResultCode,
short standbyResultCode,
LocalDateTime staleBefore
);
/**
* Poller 복구용: STANDBY_EMAIL 상태로 남아있는 최근 발송건을 다시 enqueue 하기 위해 사용
*/

View File

@@ -0,0 +1,150 @@
package com.kri.notihub.server.scheduler;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonSendRequestDto;
import com.kri.notihub.server.dto.send.DestInfoDto;
import com.kri.notihub.server.dto.send.SendInternalResultDto;
import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository;
import com.kri.notihub.server.service.SendEmailService;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class EmailBulkSendScheduler {
private final SendEmailService sendEmailService;
private final SendRepository sendRepository;
private final BulkSendRepository bulkSendRepository;
@Value("${kri.email.bulk-send.batch-size:500}")
private int batchSize;
@Value("${kri.email.bulk-send.sending-stale-minutes:30}")
private long sendingStaleMinutes;
@Scheduled(fixedDelayString = "${kri.email.bulk-send.fixed-delay-ms:10000}")
public void sendBulkEmail() {
recoverStaleSending();
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
List<TSendEntity> standbyList = sendRepository.findBulkStandbySendEmail(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_STANDBY,
now,
PageRequest.of(0, Math.max(1, batchSize))
);
for (TSendEntity send : standbyList) {
if (!tryMarkSending(send)) {
continue;
}
SendInternalResultDto sendResult = sendEmail(send);
applySendResult(send, sendResult);
sendRepository.save(send);
if (sendResult.getStatus() == SendStatusType.FAIL) {
increaseBulkFailCount(send.getBulkSendKey(), now);
} else {
sendEmailService.afterPersistSendEntities(List.of(send));
}
sleepSilently(NotihubConst.EMAIL_DELAY);
}
}
private void recoverStaleSending() {
LocalDateTime staleBefore = DateTimeUtil.nowKstLocalDateTime()
.minusMinutes(Math.max(1, sendingStaleMinutes));
sendRepository.recoverStaleBulkEmailSending(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_SENDING,
NotihubConst.EMAIL_STANDBY,
staleBefore
);
}
private boolean tryMarkSending(TSendEntity send) {
if (send == null || send.getSendIdx() == null) {
return false;
}
int updated = sendRepository.markEmailSending(
send.getSendIdx(),
NotihubConst.EMAIL_STANDBY,
NotihubConst.EMAIL_SENDING
);
if (updated != 1) {
return false;
}
send.setResultCode(NotihubConst.EMAIL_SENDING);
return true;
}
private SendInternalResultDto sendEmail(TSendEntity send) {
PringoJsonSendRequestDto pringoReq = sendEmailService.buildPringoSendRequest(
send.getSendEml(),
send.getSendNm(),
send.getMsgTitle(),
send.getMsgBody(),
DestInfoDto.from(send)
);
return sendEmailService.sendPringoEmail(pringoReq);
}
private void applySendResult(TSendEntity send, SendInternalResultDto sendResult) {
send.setCmid(sendResult.getCmid());
send.setSendStatus(sendResult.getStatus().getCode());
send.setResultCode(sendResult.getResultCode());
}
private void increaseBulkFailCount(String bulkSendKey, LocalDateTime now) {
if (bulkSendKey == null || bulkSendKey.isBlank()) {
return;
}
bulkSendRepository.findByBulkSendKey(bulkSendKey).ifPresent(bulk -> {
int fail = bulk.getFailCnt() == null ? 0 : bulk.getFailCnt();
bulk.setFailCnt(fail + 1);
completeBulkIfNeeded(bulk, now);
bulkSendRepository.save(bulk);
});
}
private void completeBulkIfNeeded(TBulkSendEntity bulk, LocalDateTime now) {
if (bulk.getCompleteDt() != null) {
return;
}
int sendCnt = bulk.getSendCnt() == null ? 0 : bulk.getSendCnt();
int successCnt = bulk.getSuccesCnt() == null ? 0 : bulk.getSuccesCnt();
int failCnt = bulk.getFailCnt() == null ? 0 : bulk.getFailCnt();
if (sendCnt <= successCnt + failCnt) {
bulk.setCompleteDt(now);
}
}
private void sleepSilently(long ms) {
if (ms <= 0) {
return;
}
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

View File

@@ -64,8 +64,8 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
String msgBody,
DestInfoDto dest
) {
if (Boolean.TRUE.equals(isResve)) {
//예약 용 cmid 생성 추후 실제 발송 후 갱신
if (Boolean.TRUE.equals(isResve) || !StringUtil.isNullOrBlank (bulkSendKey)) {
//예약 또는 bulk send 용 cmid 생성 추후 실제 발송 후 갱신
String ts = DateTimeUtil.nowKstLocalDateTime()
.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));