Merge branch 'bo_sms-auto-send' into 'dev'

[배치] 중복 실행 방지 로직 추가 (다중 톰캣 대응)

See merge request korea-research/korea-research!143
This commit is contained in:
이강선 매니저/ST
2025-07-23 05:09:33 +00:00
12 changed files with 224 additions and 75 deletions

View File

@@ -0,0 +1,17 @@
package app.module.admin.usecase.batchCheck.adapters.persistence;
import lombok.RequiredArgsConstructor;
import app.module.admin.usecase.batchCheck.ports.application.domain.BatchCheckOutCmd;
import app.module.admin.usecase.batchCheck.ports.BatchCheckPortOut;
import org.springframework.stereotype.Repository;
@Repository
@RequiredArgsConstructor
class BatchCheckDao implements BatchCheckPortOut {
private final BatchCheckMapper mapper;
@Override
public void operate(BatchCheckOutCmd outCmd) {
mapper.create(outCmd);
}
}

View File

@@ -0,0 +1,9 @@
package app.module.admin.usecase.batchCheck.adapters.persistence;
import app.module.admin.usecase.batchCheck.ports.application.domain.BatchCheckOutCmd;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BatchCheckMapper {
void create(BatchCheckOutCmd outCmd);
}

View File

@@ -0,0 +1,7 @@
package app.module.admin.usecase.batchCheck.ports;
import app.module.admin.usecase.batchCheck.ports.application.domain.BatchCheckInCmd;
public interface BatchCheckPortIn {
boolean operate(BatchCheckInCmd inCmd);
}

View File

@@ -0,0 +1,7 @@
package app.module.admin.usecase.batchCheck.ports;
import app.module.admin.usecase.batchCheck.ports.application.domain.BatchCheckOutCmd;
public interface BatchCheckPortOut {
void operate(BatchCheckOutCmd outCmd);
}

View File

@@ -0,0 +1,51 @@
package app.module.admin.usecase.batchCheck.ports.application;
import app.module.admin.usecase.batchCheck.ports.application.domain.BatchCheckInCmd;
import app.module.admin.usecase.batchLog.ports.BatchLogPortIn;
import java.net.InetAddress;
import lombok.RequiredArgsConstructor;
import app.module.admin.usecase.batchCheck.ports.application.domain.BatchCheckOutCmd;
import app.module.admin.usecase.batchCheck.ports.BatchCheckPortIn;
import app.module.admin.usecase.batchCheck.ports.BatchCheckPortOut;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
@Slf4j
class BatchCheckService implements BatchCheckPortIn {
private final BatchCheckPortOut portOut;
private final BatchLogPortIn batchLogPortIn;
@Override
public boolean operate(BatchCheckInCmd inCmd) {
try {
portOut.operate(new BatchCheckOutCmd(inCmd.getType(), inCmd.getRunDate()));
return true;
} catch (DuplicateKeyException e) {
log.warn("{} 가 이미 실행 중입니다. 중복 실행을 건너뜁니다.", inCmd.getMethodName());
batchLogPortIn.createError(inCmd.getType(), getHostName(), "WARNING",
inCmd.getMethodName() + " 가 이미 실행 중입니다. 중복 실행을 건너뜁니다.");
return false;
} catch (Exception e) {
log.error("중복 실행 체크 예외 발생 : {} / {}", inCmd.getMethodName(), e.getMessage(), e);
batchLogPortIn.createError(inCmd.getType(), getHostName(), "ERROR",
inCmd.getMethodName() + " 중복 체크 중 예외 발생: " + e.getMessage());
return false;
}
}
private String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
return "unknown";
}
}
}

View File

@@ -0,0 +1,18 @@
package app.module.admin.usecase.batchCheck.ports.application.domain;
import app.module.admin.usecase.batchLog.ports.application.domain.BatchLogType;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode
public class BatchCheckInCmd {
private String methodName;
private BatchLogType type;
private Date runDate;
}

View File

@@ -0,0 +1,17 @@
package app.module.admin.usecase.batchCheck.ports.application.domain;
import app.module.admin.usecase.batchLog.ports.application.domain.BatchLogType;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode
public class BatchCheckOutCmd {
private BatchLogType type;
private Date runDate;
}

View File

@@ -1,10 +1,14 @@
package app.module.admin.usecase.schedule.autoSchedules.adapters.web;
import app.module.admin.usecase.batchCheck.ports.BatchCheckPortIn;
import app.module.admin.usecase.batchCheck.ports.application.domain.BatchCheckInCmd;
import app.module.admin.usecase.batchLog.ports.BatchLogPortIn;
import app.module.admin.usecase.batchLog.ports.application.domain.BatchLogType;
import app.module.admin.usecase.schedule.autoSchedules.ports.AutoSchedulesPortIn;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@@ -13,23 +17,18 @@ import org.springframework.stereotype.Component;
public class AutoSchedulesController {
private final AutoSchedulesPortIn portIn;
private final BatchLogPortIn batchLogPortIn;
private final java.util.Set<String> runningTasks = java.util.concurrent.ConcurrentHashMap.newKeySet();
private final BatchCheckPortIn batchCheckPortIn;
@Value("${spring.profiles.active}")
private String activeProfiles;
public AutoSchedulesController(AutoSchedulesPortIn portIn, BatchLogPortIn batchLogPortIn) {
@Value("${scheduler.enabled}")
private boolean schedulerEnabled;
public AutoSchedulesController(AutoSchedulesPortIn portIn, BatchCheckPortIn batchCheckPortIn) {
this.portIn = portIn;
this.batchLogPortIn = batchLogPortIn;
}
private boolean isAlreadyRunning(String lockKey) {
return !runningTasks.add(lockKey);
}
private void releaseLock(String lockKey) {
runningTasks.remove(lockKey);
}
this.batchCheckPortIn = batchCheckPortIn;
}
/**
* 월별입력상태 등록
@@ -37,33 +36,30 @@ public class AutoSchedulesController {
*/
@Scheduled(cron = "0 0 0 1 * *")
public void fetchMonthlyStatus() {
if (!"local".equals(activeProfiles)) {
log.info("fetchMonthlyStatus 는 local 환경에서는 실행되지 않습니다. (현재: {})", activeProfiles);
String methodName = "fetchMonthlyStatus";
if (!schedulerEnabled) {
log.info("{} 는 local 환경에서는 실행되지 않습니다. (현재: {})", methodName, activeProfiles);
return;
}
// 중복 실행 여부 체크
if (!batchCheckPortIn.operate(
new BatchCheckInCmd(methodName, BatchLogType.MONTHLY_STATUS, new Date()))) {
return;
}
String lockKey = "fetchMonthlyStatus_" + java.time.LocalDate.now();
try {
String host = java.net.InetAddress.getLocalHost().getHostName();
// 중복 실행 방지를 위한 간단한 체크
if (isAlreadyRunning(lockKey)) {
log.warn("fetchMonthlyStatus 가 이미 실행 중입니다. 중복 실행을 건너뜁니다.");
batchLogPortIn.createError(BatchLogType.MONTHLY_STATUS, host, "WARNING", "fetchMonthlyStatus가 이미 실행 중입니다. 중복 실행을 건너뜁니다.");
return;
}
log.info("스케줄 실행 : fetchMonthlyStatus / {} / {} / {} / {}", host, this, + System.identityHashCode(this), Thread.currentThread().getName());
log.info("스케줄 실행 : {} / {} / {} / {} / {}",
methodName, java.net.InetAddress.getLocalHost().getHostName(), this,
+System.identityHashCode(this), Thread.currentThread().getName());
// 월별입력상태 실행
portIn.operate();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
log.info("스케줄 종료 : fetchMonthlyStatus / {}", lockKey);
releaseLock(lockKey);
log.error("예외 발생 : {} / {}", methodName, e.getMessage(), e);
} finally {
log.info("스케줄 종료 : {}", methodName);
}
}
@@ -73,37 +69,30 @@ public class AutoSchedulesController {
*/
@Scheduled(cron = "0 0 17 * * ?")
public void fetchSmsAutoSend() {
// TODO : 22일 테스트용 -> 테스트후 !"local".equals(activeProfiles) 로 조건 변경
if ("dev".equals(activeProfiles)) {
log.info("fetchSmsAutoSend 는 dev 환경에서만 실행됩니다. (현재: {})", activeProfiles);
String methodName = "fetchSmsAutoSend";
if (!schedulerEnabled) {
log.info("{} 는 local 환경에서는 실행되지 않습니다. (현재: {})", methodName, activeProfiles);
return;
}
// 중복 실행 여부 체크
if (!batchCheckPortIn.operate(
new BatchCheckInCmd(methodName, BatchLogType.AUTO_SMS, new Date()))) {
return;
}
String lockKey = "fetchSmsAutoSend" + java.time.LocalDate.now();
try {
String host = java.net.InetAddress.getLocalHost().getHostName();
// [TEST] dev 환경에서 배치가 실제 실행되고 있는지 체크
batchLogPortIn.create(BatchLogType.AUTO_SMS, host, "BATCH_RUNNING");
// 중복 실행 방지를 위한 간단한 체크
if (isAlreadyRunning(lockKey)) {
log.warn("fetchSmsAutoSend 이미 실행 중입니다. 중복 실행을 건너뜁니다.");
batchLogPortIn.createError(BatchLogType.AUTO_SMS, host, "WARNING", "fetchSmsAutoSend 이미 실행 중입니다. 중복 실행을 건너뜁니다.");
return;
}
log.info("스케줄 실행 : fetchSmsAutoSend / {} / {} / {} / {}", host, this, + System.identityHashCode(this), Thread.currentThread().getName());
log.info("스케줄 실행 : {} / {} / {} / {} / {}",
methodName, java.net.InetAddress.getLocalHost().getHostName(), this,
+System.identityHashCode(this), Thread.currentThread().getName());
// 문자자동발송 실행
portIn.sendAutoSms();
} catch (Exception e) {
log.error(e.getMessage(), e);
log.error("예외 발생 : {} / {}", methodName, e.getMessage(), e);
} finally {
log.info("스케줄 종료 : fetchSmsAutoSend / {}", lockKey);
releaseLock(lockKey);
log.info("스케줄 종료 : {}", methodName);
}
}
@@ -113,33 +102,30 @@ public class AutoSchedulesController {
*/
@Scheduled(cron = "0 0 0 16 * *")
public void fetchMonthlyCarryOver() {
if (!"local".equals(activeProfiles)) {
log.info("fetchMonthlyCarryOver 는 local 환경에서는 실행되지 않습니다. (현재: {})", activeProfiles);
String methodName = "fetchMonthlyCarryOver";
if (!schedulerEnabled) {
log.info("{} 는 local 환경에서는 실행되지 않습니다. (현재: {})", methodName, activeProfiles);
return;
}
// 중복 실행 여부 체크
if (!batchCheckPortIn.operate(
new BatchCheckInCmd(methodName, BatchLogType.CARRYOVER, new Date()))) {
return;
}
String lockKey = "fetchMonthlyCarryOver_" + java.time.LocalDate.now();
try {
String host = java.net.InetAddress.getLocalHost().getHostName();
// 중복 실행 방지를 위한 간단한 체크
if (isAlreadyRunning(lockKey)) {
log.warn("fetchMonthlyCarryOver가 이미 실행 중입니다. 중복 실행을 건너뜁니다.");
batchLogPortIn.createError(BatchLogType.CARRYOVER, host, "WARNING", "fetchMonthlyCarryOver가 이미 실행 중입니다. 중복 실행을 건너뜁니다.");
return;
}
log.info("스케줄 실행 : fetchMonthlyCarryOver / {} / {} / {} / {}", host, this, + System.identityHashCode(this), Thread.currentThread().getName());
log.info("스케줄 실행 : {} / {} / {} / {} / {}",
methodName, java.net.InetAddress.getLocalHost().getHostName(), this,
+System.identityHashCode(this), Thread.currentThread().getName());
// 월초이월금 실행
portIn.monthlyCarryOver();
} catch (Exception e) {
log.error(e.getMessage(), e);
log.error("예외 발생 : {} / {}", methodName, e.getMessage(), e);
} finally {
log.info("스케줄 종료 : fetchMonthlyCarryOver / {}", lockKey);
releaseLock(lockKey);
log.info("스케줄 종료 : {}", methodName);
}
}
}

View File

@@ -46,3 +46,9 @@ jasypt:
encryptor:
password: etribe
algorithm: PBEWITHHMACSHA512ANDAES_256
# ==============================================
# local 환경에서는 배치 스케줄러 미실행
# ==============================================
scheduler:
enabled: false

View File

@@ -117,3 +117,9 @@ jasypt:
encryptor:
password: #별도관리
algorithm: #별도관리
# ==============================================
# 배치 스케줄러 실행 여부 (true: 실행, false: 미실행)
# ==============================================
scheduler:
enabled: true

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="app.module.admin.usecase.batchCheck.adapters.persistence.BatchCheckMapper" >
<insert id="create">
/* create : 배치 실행 여부 등록 */
INSERT INTO batch_check(type, run_date)
VALUES (#{type}, #{runDate})
</insert>
</mapper>

View File

@@ -431,6 +431,22 @@ COMMENT ON COLUMN batch_log.created_host IS '생성HOST';
-- ====================================================================================================================
-- 배치 실행 여부
-- ====================================================================================================================
CREATE TABLE batch_check (
type VARCHAR(50) NOT NULL,
run_date DATE NOT NULL,
PRIMARY KEY (type, run_date)
);
COMMENT ON TABLE batch_check IS '배치 실행 여부 테이블';
COMMENT ON COLUMN batch_check.type IS '배치 타입';
COMMENT ON COLUMN batch_check.run_date IS '배치 실행 날짜';
-- ====================================================================================================================
-- 엑셀용 view 생성