Loading the catalog…
Loading the catalog…
🎯 핵심 키워드 키워드 내용 API Gateway 클라이언트의 요청을 받아 라우팅, 인증, 권한 부여, 부하 분산(Load Balancing), 로깅 등 공통 기능(횡단 관심사)을 수행하는 최전방 프록시 서버 Spring Cloud Gateway Spring 진영의 비동기 (Non-blocking) 방식 게이트웨이 WebFlux 기반으로 적은 스레드로 많은 요청을 처리할 수 있다. Route / Predicate / Filter - Route : 목적지 URL(uri) 설정 - Predicate : 조건식 ( ex. Path=/first-service/** ) - Filter : 요청/응답을 가로채어 조작(Header 추가, 인증, 로깅 등)하는 컴포넌트 Load Balancing (lb://) 유레카(Eureka)에 등록된 다수의 서비스 인스턴스(서버) 중 트래픽을 분산시켜 주는 기능 📖 오늘 배운 내용 1. API Gateway 동작 및 Filter 흐름 분석 API Gateway 역할 ↓ Spring Cloud Gateway ↓ Route / Predicate ↓ Request / Response Filter ↓ Custom Filter ↓ Global Filter ↓ Eureka 연동 ↓ Service Name 기반 Routing ↓ Load Balancing [Filter 동작 순서 상세 (Pre & Post)] 게이트웨이는 비즈니스 로직(마이크로서비스)을 호출하기 전/후에 필터를 거친다. Request(요청) 방향 (Pre Filter) : Client ➔ Global Pre ➔ Custom Pre ➔ Logging Pre ➔ Business Logic(Microservice) Response(응답) 방향 (Post Filter) : Business Logic ➔ Logging Post ➔ Custom Post ➔ Global Post ➔ Client 2. Spring Cloud Gateway 설정 및 유레카 연동 (apigateway-service) 게이트웨이 자체도 유레카 클라이언트로 등록되어야 하며, 들어오는 요청을 lb:// 프로토콜을 통해 유레카에 등록된 서비스 이름(Service Name)으로 라우팅해야 로드 밸런싱이 동작한다 [application.yml 설정] server: port: 8000 # 게이트웨이는 고정 포트(8000) 사용 eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka instance: prefer-ip-address: true # 호스트명 대신 IP로 등록 spring: application: name: apigateway-service cloud: gateway: default-filters: # Global Filter 설정 (모든 라우트에 공통 적용) - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Webflux Global Filter preLogger: true postLogger: true routes: - id: first-service # uri: http://localhost:8081/ (직접 호출 방식은 주석 처리) uri: lb://MY-FIRST-SERVICE # 유레카 연동: lb://서비스이름 (로드 밸런싱) predicates: - Path=/first-service/** filters: - CustomFilter - id: second-service uri: lb://MY-SECOND-SERVICE predicates: - Path=/second-service/** filters: - name: CustomFilter - name: LoggingFilter # Logging Filter 추가 args: baseMessage: Hi, there. preLogger: true postLogger: true 3. Filter 구현 (Global, Custom, Logging) Spring Cloud Gateway의 필터는 AbstractGatewayFilterFactory를 상속받아 구현한다. * 1. Global Filter * 모든 라우팅에 기본적으로 적용되는 필터 @Component @Slf4j public class GlobalFilter extends AbstractGatewayFilterFactory<GlobalFilter.Config> { // ... 생성자 생략 ... @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); // Custom Pre Filter: 인증 검사, 헤더추가, 로깅 등을 여기서 처리 log.info("Global Filter baseMessage: {}, {}", config.getBaseMessage(), request.getRemoteAddress()); if (config.isPreLogger()) { log.info("Global Filter Start: request id -> {}", request.getId()); } // Custom Post Filter: 체인이 끝난 후 비동기로 실행 return chain.filter(exchange).then(Mono.fromRunnable(() -> { if (config.isPostLogger()) { log.info("Global Filter End: response code -> {}", response.getStatusCode()); } })); }; } // ... Config 클래스 생략 ... } 2. Logging Filter와 우선순위(Ordered) 특정 라우트에만 적용되는 필터이며, OrderedGatewayFilter를 사용해 필터의 실행 순서를 강제로 지정할 수 있다 @Component @Slf4j public class LoggingFilter extends AbstractGatewayFilterFactory<LoggingFilter.Config> { // ... 생략 ... /* 우선 순위를 갖는 Logging Filter 적용 */ @Override public GatewayFilter apply(Config config) { OrderedGatewayFilter filter = new OrderedGatewayFilter((exchange, chain) -> { // ... (Pre/Post 로깅 로직은 Global Filter와 유사) ... return chain.filter(exchange).then(Mono.fromRunnable(() -> { if (config.isPostLogger()) { log.info("Logging Filter End: response code -> {}", response.getStatusCode()); } })); }, Ordered.HIGHEST_PRECEDENCE); // 가장 먼저(Highest) 실행되도록 우선순위 강제 조정 return filter; } } 4. Microservice 연동 및 Load Balancing 테스트 First Service와 Second Service를 각각 여러 대(포트 0 랜덤) 띄운 후, http://localhost:8000 (gateway) 를 통해 요청을 보냈을 때 로드 밸런싱이 되는지 확인했다 [Microservice application.yml] server: port: 0 # 랜덤 포트 설정 spring: application: name: my-second-service # 유레카에 등록될 서비스명 (게이트웨이의 lb:// 주소와 매칭됨) eureka: instance: # 고유 식별자를 부여하여 다중 인스턴스가 유레카에 개별적으로 등록되게 함 instance-id: ${spring.cloud.client.ip-address}:${spring.application.instance_id:${random.value}} [테스트 결과] Postman을 이용해 GET http://localhost:8000/first-service/check 형식으로 Gateway에 요청을 여러 번 보내면, 게이트웨이가 유레카에서 서비스 인스턴스 목록을 받아와 라운드 로빈(Round Robin) 방식 으로 포트를 번갈아가며(ex: 52887 ➔ 52888) 응답하는 것을 확인할 수 있었다. 이는 Gateway와 Eureka를 통한 완벽한 로드 밸런싱이 수행됨을 의미한다
What RADAR observed and classified to build this opportunity. It is what the source published, not a verification that the offer is still active.
[LG CNS AM INSPIRE CAMP 6기] DAY 38 - Spring Cloud Gateway 실습. 🎯 핵심 키워드 키워드 내용 API Gateway 클라이언트의 요청을 받아 라우팅, 인증, 권한 부여, 부하 분산(Load Balancing), 로깅 등 공통 기능(횡단 관심사)을 수행하는 최전방 프록시 서버 Spring Cloud Gateway Spring 진영의 비동기 (Non-blocking) 방식 게이트웨이 WebFlux 기반으로 적은 스레드로 많은 요청을 처리할 수 있다. Route / Predicate / Filter - Route : 목적지 URL(uri) 설정 - Predicate : 조건식 ( ex. Path=/first-service/** ) - Filter : 요청/응답을…
Open source