MSA 4일차 : 스프링 클라우드 - API Gateway

parang·2025년 5월 29일

LG CNS AM Inspire Camp 2기

목록 보기
36/50
이번 시간에는 API Gateway를 적용해서 프로젝트를 구성하는 실습을 진행하였다. 
또한 코드를 작성하면서 
이전과는 조금 더 실무적인 포인트를 많이 접해서 좋았다.

API Gateway

Api gateway는 클라이언트가 애플리케이션에 api 요청을 하는 단일 창구 역할을 하는 서비스이다. 또한 인증, 모니터링 등 부수적인 일도 담당한다.

이전 프로젝트까지는 방어벽 없이 직접 서비스로 접근하는 방식으로 통신했다. API Gateway는 그것을 방지하기 위해 방어벽을 중간에 하나 세웠다고 생각하면 된다.

담당 하는 것

  • 요청 라우팅
  • api조합
  • 프로토콜 변환
  • 검증

API Gateway 프로젝트 생성

의존성

추가하는 의존성으로는 아래 그림과 같다.

Gateway라는 새로운 의존성이 추가되었다.

생성 후에는, 이전 프로젝트 처럼 자바 17을 사용하는 것을 체크 하고 메인 애플리케이션에 @EnableDiscoveryClient을 추가한다.

application-local.yml

server:
  port: 8080
eureka:
  instance:
    prefer-ip-address: true
  client:
    register-with-eureka: true
    fetch-registry: true
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
spring:
  cloud:
    gateway:
      mvc: 
        routes: # 라우팅 설정
          - id: backend-user # 첫 번째 라우트
            uri: lb://backend-user # 요청을 전달할 대상 URI입니다. 
            predicates: # 라우트가 적용될 조건
              - Path=/api/user/** 
          - id: backend-alim 
            uri: lb://backend-alim 
            predicates: 
              - Path=/api/alim/**

게이트웨이 설정은 이걸로 끝이다.

backend-user 데이터 베이스 연결 yml

spring:
  datasource:
    url: jdbc:mysql://localhost:13306/user?serverTimezone=UTC&useSSL=true&autoReconnect=true&useUnicode=true&characterEncoding=utf-8
    username: user
    password: 1234
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      connection-test-query: SELECT 1 # HikariCP 유효성 검사 추가
      validation-timeout: 5000
  jpa:
    hibernate:
      ddl-auto: create # 오직 테스트 환경에서만
    generate-ddl: true # 오직 테스트 환경에서만 (spring.jpa.generate-ddl)
    show-sql: true
    open-in-view: false

오류 응답 메시지 정규화

코드를 작성하다 보면 여러 에러나 예외상황이 아주 많이 발생한다. 
따라서 따로 빼서 관리하는 것이 아주 효율적이다.
이전 미니 프로젝트에도 서버 에러가 나면 어디서 에러가 난 건지 확인할 수가 없어 
에러 코드를 따로 빼서 작성했었는데 
이번 기회로 제대로 접할 수 있어서 매우 좋았던 실습이었다.

ApiError

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED) 
public class ApiError extends RuntimeException{
    protected String errorCode;
    protected String errorMessage;
}
-> 런타임 예외를 상속받는 예외 커스텀 파일이다.

ClientError

@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class ClientError extends ApiError {
}
-> ApiError를 상속받는다.
  • ApiError를 상속받는 BadParameter

  • ClientError 를 상속받는 NotFound` 예외 클래스 생성

BadParameter

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class BadParameter extends ClientError {
    public BadParameter(String message){
        this.errorCode = "Bad Parameter";
        this.errorMessage = message;
    }
}

NotFound

public class NotFound extends ClientError{
    public NotFound(String message){
        this.errorCode = "Not Found";
        this.errorMessage = message;
    }
}
profile
파랑입니다.

0개의 댓글