first commit

This commit is contained in:
2025-11-12 15:53:31 +09:00
commit a2a9402270
22 changed files with 911 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
package com.kri.common.redis;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
@AutoConfiguration
@ConditionalOnClass(RedisTemplate.class)
@ConditionalOnProperty(prefix = "common.redis", name = "enabled", havingValue = "true", matchIfMissing = false)
@ConditionalOnBean(RedisConnectionFactory.class)
public class CommonRedisAutoConfiguration {
@Bean @ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(org.springframework.data.redis.connection.RedisConnectionFactory cf) {
return new StringRedisTemplate(cf);
}
@Bean @ConditionalOnMissingBean
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { return new RedisQueueHelper(rt); }
}

View File

@@ -0,0 +1,11 @@
package com.kri.common.redis;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.time.Duration;
public class RedisQueueHelper {
private final StringRedisTemplate rt;
public RedisQueueHelper(StringRedisTemplate rt){ this.rt = rt; }
public void enqueue(String key, String value){ rt.opsForList().rightPush(key, value); }
public String blockingDequeue(String key, Duration timeout){ return rt.opsForList().leftPop(key, timeout); }
}

View File

@@ -0,0 +1,10 @@
package com.kri.common.scheduling;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling;
@AutoConfiguration
@EnableScheduling
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false)
public class CommonSchedulingAutoConfiguration { }

View File

@@ -0,0 +1,51 @@
package com.kri.common.web;
import org.springframework.http.HttpStatus;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class BusinessException extends RuntimeException {
private final HttpStatus status;
private final String code;
private final Map<String, Object> extras;
private static String defaultCode(HttpStatus status) { return status.name(); } // 예: NOT_FOUND, CONFLICT …
private BusinessException(HttpStatus status, String code, String message,
Map<String, Object> extras, Throwable cause) {
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
this.status = status;
this.code = (code != null && !code.isBlank()) ? code : defaultCode(status); // 코드가 없으면 상태명으로 대체
this.extras = extras == null ? Collections.emptyMap()
: Collections.unmodifiableMap(new HashMap<>(extras));
}
public static BusinessException of(HttpStatus status, String code, String message) {
return new BusinessException(status, code, message, null, null);
}
public static BusinessException of(HttpStatus status, String code, String message, Map<String,Object> extras) {
return new BusinessException(status, code, message, extras, null);
}
// 편의 생성자들
public static BusinessException notFound(String code, String message) {
return of(HttpStatus.NOT_FOUND, code, message);
}
public static BusinessException conflict(String code, String message) {
return of(HttpStatus.CONFLICT, code, message);
}
public static BusinessException forbidden(String code, String message) {
return of(HttpStatus.FORBIDDEN, code, message);
}
public HttpStatus getStatus(){ return status; }
public String getCode(){ return code; }
public Map<String, Object> getExtras(){ return extras; }
/** 편의: 체이닝으로 extras 추가 */
public BusinessException with(String key, Object value) {
var map = new HashMap<>(this.extras);
map.put(key, value);
return new BusinessException(this.status, this.code, this.getMessage(), map, this.getCause());
}
}

View File

@@ -0,0 +1,18 @@
package com.kri.common.web;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.core.Ordered;
@AutoConfiguration
@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true)
public class CommonWebAutoConfiguration {
@Bean public ErrorAdvice errorAdvice() { return new ErrorAdvice(); }
@Bean public FilterRegistrationBean<TraceFilter> traceFilter() {
var reg = new FilterRegistrationBean<>(new TraceFilter());
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
return reg;
}
}

View File

@@ -0,0 +1,200 @@
package com.kri.common.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@RestControllerAdvice
public class ErrorAdvice {
private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class);
// 기본값은 모두 false → 외부 응답엔 노출 안 함
@Value("${common.error.expose.handler:false}")
private boolean exposeHandler;
@Value("${common.error.expose.service:false}")
private boolean exposeService;
/* ---------- 공통 ProblemDetail 빌더 ---------- */
protected ProblemDetail pd(HttpStatus status, String code, String message,
HttpServletRequest req, Map<String, Object> extras) {
ProblemDetail p = ProblemDetail.forStatusAndDetail(status, message);
p.setTitle(status.getReasonPhrase());
p.setProperty("code", code);
p.setProperty("timestamp", Instant.now().toString());
p.setProperty("path", req.getRequestURI());
String traceId = MDC.get("traceId");
if (traceId != null) p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
// ↓↓↓ 외부로 숨기고 싶으면 기본 false
if (exposeHandler) {
String handler = MDC.get("handler"); // Controller#method
if (handler != null) p.setProperty("handler", handler);
}
if (exposeService) {
String service = MDC.get("service"); // Service#method (최초 진입)
if (service != null) p.setProperty("service", service);
}
if (extras != null) extras.forEach(p::setProperty);
return p;
}
/* ---------- Custom Exception ---------- */
@ExceptionHandler(BusinessException.class)
public ProblemDetail handleBusiness(BusinessException e, HttpServletRequest req) {
logBusiness(e, req); // ← 로그 먼저
return pd(
e.getStatus(),
e.getCode(), // 문자열 코드(없으면 상태명으로 이미 대체됨)
e.getMessage(),
req,
e.getExtras().isEmpty() ? null : e.getExtras()
);
}
/* 상황별 로그 레벨/스택트레이스 정책 */
private void logBusiness(BusinessException e, HttpServletRequest req) {
int sc = e.getStatus().value();
String traceId = MDC.get("traceId");
String path = req.getRequestURI();
String code = e.getCode();
var extras = e.getExtras();
if (sc >= 500) {
// 5xx: 운영 이슈 → ERROR + 스택트레이스
log.error("BusinessException status={} code={} path={} traceId={} extras={}",
sc, code, path, traceId, extras, e);
} else if (sc == 409 || sc == 404 || sc == 400 || sc == 403 || sc == 422) {
// 사용자/도메인 입력 문제 → WARN, 스택트레이스 제외
log.warn("BusinessException status={} code={} path={} traceId={} extras={}",
sc, code, path, traceId, extras);
} else {
// 기타 → WARN 기본
log.warn("BusinessException status={} code={} path={} traceId={} extras={}",
sc, code, path, traceId, extras);
}
}
/* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest req) {
var fieldErrors = e.getBindingResult().getFieldErrors().stream()
.map(fe -> Map.of(
"field", fe.getField(),
"message", Optional.ofNullable(fe.getDefaultMessage()).orElse("invalid"),
"rejectedValue", String.valueOf(fe.getRejectedValue())
))
.collect(Collectors.toList());
return pd(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "요청 데이터가 올바르지 않습니다.", req,
Map.of("errors", fieldErrors));
}
/* ---------- 400: 파라미터/타입 문제 ---------- */
@ExceptionHandler({
MissingServletRequestParameterException.class,
HttpMessageNotReadableException.class
})
public ProblemDetail handleBadRequest(RuntimeException e, HttpServletRequest req) {
String msg = (e instanceof HttpMessageNotReadableException)
? "요청 바디를 읽을 수 없습니다(형식 오류/잘못된 JSON)."
: e.getMessage();
return pd(HttpStatus.BAD_REQUEST, "BAD_REQUEST", msg, req, null);
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e, HttpServletRequest req) {
String need = (e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type";
String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need;
return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null);
}
/* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handleConstraintViolation(ConstraintViolationException e, HttpServletRequest req) {
var errors = e.getConstraintViolations().stream()
.map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage()))
.collect(Collectors.toList());
return pd(HttpStatus.BAD_REQUEST, "CONSTRAINT_VIOLATION", "요청 파라미터가 제약을 위반했습니다.", req,
Map.of("errors", errors));
}
/* ---------- 404/405/415 등 표준 스프링 예외 ---------- */
@ExceptionHandler(NoHandlerFoundException.class)
public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) {
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest req) {
String supported = resolveSupportedMethods(e);
String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported;
// 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported)
return pd(HttpStatus.METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED", msg, req, null);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e, HttpServletRequest req) {
String supported = e.getSupportedMediaTypes().stream().map(Object::toString).collect(Collectors.joining(","));
String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported;
return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null);
}
/* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */
@ExceptionHandler({ ResponseStatusException.class, ErrorResponseException.class })
public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) {
HttpStatus status;
String reason;
if (e instanceof ResponseStatusException rse) {
status = HttpStatus.valueOf(rse.getStatusCode().value());
reason = Optional.ofNullable(rse.getReason()).orElse(status.getReasonPhrase());
} else { // ErrorResponseException (Spring 6+)
var ere = (ErrorResponseException) e;
status = HttpStatus.valueOf(ere.getStatusCode().value());
reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail).orElse(status.getReasonPhrase());
}
return pd(status, "ERROR", reason, req, null);
}
/* ---------- 마지막: 예상 못한 예외는 500 ---------- */
@ExceptionHandler(Exception.class)
public ProblemDetail handleAny(Exception e, HttpServletRequest req) {
return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null);
}
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
Set<HttpMethod> httpMethods = e.getSupportedHttpMethods();
if (httpMethods != null && !httpMethods.isEmpty()) {
// ✅ 핵심 수정: Enum::name 대신 HttpMethod::name
return httpMethods.stream()
.map(HttpMethod::name)
.collect(Collectors.joining(", "));
}
String[] methods = e.getSupportedMethods(); // 구버전 호환용
if (methods != null && methods.length > 0) {
return String.join(", ", methods);
}
return "N/A";
}
}

View File

@@ -0,0 +1,33 @@
package com.kri.common.web;
import jakarta.servlet.http.*;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.*;
public class MdcHandlerConfig {
@Bean
public WebMvcConfigurer mdcWebMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
if (handler instanceof HandlerMethod hm) {
String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController
String method = hm.getMethod().getName(); // ex) create
MDC.put("handler", ctrl + "#" + method); // ex) ContactController#create
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
MDC.remove("handler");
}
});
}
};
}
}

View File

@@ -0,0 +1,25 @@
package com.kri.common.web;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ServiceMdcAspect {
@Around("within(@org.springframework.stereotype.Service *)")
public Object aroundService(ProceedingJoinPoint pjp) throws Throwable {
boolean first = (MDC.get("service") == null);
if (first) {
String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService
String mtd = pjp.getSignature().getName(); // ex) enqueue
MDC.put("service", cls + "#" + mtd); // ex) ExportService#enqueue
}
try {
return pjp.proceed();
} finally {
if (first) MDC.remove("service");
}
}
}

View File

@@ -0,0 +1,28 @@
package com.kri.common.web;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import java.io.IOException;
import java.util.UUID;
public class TraceFilter implements Filter {
private static final String REQ_HEADER = "X-Request-Id";
private static final String MDC_KEY = "traceId";
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
var httpReq = (HttpServletRequest) req;
var httpRes = (HttpServletResponse) res;
String id = httpReq.getHeader(REQ_HEADER);
if (id == null || id.isBlank()) id = UUID.randomUUID().toString();
try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) {
httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo
chain.doFilter(req, res);
}
}
}

View File

@@ -0,0 +1,3 @@
com.kri.common.web.CommonWebAutoConfiguration
com.kri.common.redis.CommonRedisAutoConfiguration
com.kri.common.scheduling.CommonSchedulingAutoConfiguration

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
<!-- Spring property 사용 (없으면 기본값) -->
<springProperty scope="context" name="APP_NAME" source="app.name" defaultValue="app"/>
<springProperty scope="context" name="LOG_DIR" source="logging.file.path" defaultValue="logs"/>
<!-- 공통 패턴: traceId/handler/service(MDC) 포함 -->
<property name="LOG_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [%X{handler}] [%X{service}] %-5level %logger{36} - %msg%n"/>
<!-- 콘솔 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- Spring Boot 확장 패턴도 사용할 수 있음: %clr(%level) 등 -->
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- 롤링 파일 (일 단위) -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_DIR}/${APP_NAME}.log</file>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}.log.gz</fileNamePattern>
<maxHistory>14</maxHistory> <!-- 보관 일수 -->
</rollingPolicy>
</appender>
<!-- (권장) 비동기 래핑: 파일 I/O를 비동기로 -->
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>8192</queueSize>
<discardingThreshold>0</discardingThreshold>
<neverBlock>true</neverBlock>
<appender-ref ref="FILE"/>
</appender>
<!-- 패키지별 레벨(선택) -->
<!-- <logger name="com.kri" level="INFO" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ASYNC_FILE"/>
</logger> -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ASYNC_FILE"/>
</root>
</configuration>