728x90
0.추가 이유
Redis 연결 오류에 대한 예외처리가 @ControllerAdvice를 사용한 GlobalExceptionHandler에서 안잡히고 로그를 저렇게 더럽혀서 Spring MVC 컨트롤러에서 발생한 예외가 아닌 redis 예외를 처리할 클래스를 생성하기로 했음
여기서 Filter 계층에서 redis 예외가 발생하는거같은데 이건 @ControllerAdvice 또는 @ExceptionHandler로 처리할수없다.
[클라이언트 요청] → [Filter] → [Spring Security 필터] → [DispatcherServlet (Spring MVC)]
이건 @ControllerAdvice 또는 @ExceptionHandler에서 처리가능한 영역
[DispatcherServlet] → [Controller] → [Service] → [Repository] → (예외 발생)
1.ExceptionCatchingFilter
Spring Boot의 필터(Filter)에서 발생하는 예외를 잡아 처리하는 역할을 수행하는 클래스를 생성했다.
filterChain.doFilter()를 수행하다가 Redis 연결 오류가 발생하면 로그를 띄어준다.
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionCatchingFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(ExceptionCatchingFilter.class);
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (RedisConnectionFailureException ex) {
log.error("Redis connection error: {}", ex.getMessage());
response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(), "Redis server is unavailable.");
} catch (Exception ex) {
log.error("Unexpected error: {}", ex.getMessage());
throw ex;
}
}
}
2.필터 설정
이건 @Component를 사용하지않았을때 수동으로 필터를 등록하는 설정인데
나는 별도 추가 설정을 하지않을것이기 떄문에 해당 코드는 주석으로만 남겨두고 사용은 안할거임
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<ExceptionCatchingFilter> exceptionCatchingFilter() {
FilterRegistrationBean<ExceptionCatchingFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new ExceptionCatchingFilter());
registrationBean.addUrlPatterns("/*"); // 모든 URL에 적용
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); // 최우선 적용
return registrationBean;
}
}
이제 Redis 예외가 발생했을때 내가 설정한 간단한 로그로 출력하게 해서 가독성좋게 볼수있어졌다.
[ERROR] 2025-03-23 16:25:54 [c.s.filter.ExceptionCatchingFilter] - Redis connection error: Unable to connect to Redis
3. Redis 서버에 연결확인 리스너
프로젝트 실행할때마다 계속 깜빡하고 Docker로 Redis를 실행하는것을 까먹고 엔드포인트에 테스트 접근할때 아. 하게 되는 상황이 몇번 일어나서 SpringBoot 프로젝트를 실행하면 Redis 에 접근을 시도하여 실패시 에러 로그를 띄어주는 이벤트 리스너를 만들것이다.
ApplicationListener<ApplicationReadyEvent>를 구현하면 springboot 가 완전 실행후 실행된다.
springboot가 실행되면 onApplicationEvent가 메소드가 자동 호출된다.
@Component
@Log4j2
public class RedisStartupListener implements ApplicationListener<ApplicationReadyEvent> {
private final RedisConnectionFactory redisConnectionFactory;
public RedisStartupListener(RedisConnectionFactory redisConnectionFactory) {
this.redisConnectionFactory = redisConnectionFactory;
}
@Override
public void onApplicationEvent(@NonNull ApplicationReadyEvent event) {
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
if (connection.ping() != null) {
log.info("Redis Connection Success");
} else {
log.warn("Redis Connection Error");
}
} catch (Exception e) {
log.error("Redis Connet Error");
}
}
}
이제 실행했을때 Redis가 안켜져있으면 다음과같은 에러 로그를 받아 확인할수있게 되었다!
728x90
'BackEnd > SpringBoot' 카테고리의 다른 글
[SpringBoot] Swagger 인증 유지 설정 (0) | 2025.03.23 |
---|---|
[SpringBoot] redis + 스케쥴링으로 조회수 관리 (0) | 2025.03.17 |
[SpringBoot] 이미지 업로드 기능만들기 (0) | 2025.03.16 |