first commit
This commit is contained in:
@@ -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); }
|
||||
}
|
||||
11
src/main/java/com/kri/common/redis/RedisQueueHelper.java
Normal file
11
src/main/java/com/kri/common/redis/RedisQueueHelper.java
Normal 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); }
|
||||
}
|
||||
@@ -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 { }
|
||||
51
src/main/java/com/kri/common/web/BusinessException.java
Normal file
51
src/main/java/com/kri/common/web/BusinessException.java
Normal 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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
200
src/main/java/com/kri/common/web/ErrorAdvice.java
Normal file
200
src/main/java/com/kri/common/web/ErrorAdvice.java
Normal 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";
|
||||
}
|
||||
}
|
||||
33
src/main/java/com/kri/common/web/MdcHandlerConfig.java
Normal file
33
src/main/java/com/kri/common/web/MdcHandlerConfig.java
Normal 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");
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
25
src/main/java/com/kri/common/web/ServiceMdcAspect.java
Normal file
25
src/main/java/com/kri/common/web/ServiceMdcAspect.java
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
28
src/main/java/com/kri/common/web/TraceFilter.java
Normal file
28
src/main/java/com/kri/common/web/TraceFilter.java
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user