본문 바로가기

spring/cloud

[spring cloud]#4 spring cloud gateway 구축하기

Spring cloud gateway 매커니즘

spring cloud gateway는 세가지 요소로 구성되어 있다.

 

1. Route : 어떤 요청에 대해서 어떻게 처리할지에 대한 설정을 구성하는 하나의 기초적인 단위

2. Predicate : 어떤 요청을 처리할 지를 결정하는 요소

3. Filter : 요청을 어떻게 처리할 지 그리고 그 응답에 대해서 어떤 사후 처리를 할지를 결정하는 요소

 

Gateway Handler Mapping 에서 어떤 Route에 매칭을 해하는지 결정하여 Route에 명시된 설정에 따른 Handler를 통해서 요청을 처리하게 되는 매커니즘으로 구성되어 있다.

 

predicate : 어떤 요청을 처리할까?

predicate index

Spring cloud gateway에서는 다음과 같이 구현된 Predicate를 이용해서 간단한 설정으로 요청을 식별하는 기능을 제공한다. 공식문서에서 각 예제와 설명을 참고하면 원하는 Predicate를 참조할 수 있다.

 

Filter : 어떻게 요청을 처리할까?

filter sample

들어온 요청을 어떻게 처리할지데 대한 필터 클래스 역시 이미 구현된 기능이 존재한다. 30개 이상의 필터들이 각 역할에 맞게 구현되어 있기 때문에 필요한 필터를 사용하여 요청을 처리할 수 있다.


간단한 API GATEWAY 구현하기

 

간단한 api gateway를 구현해보자.

 

요구사항

http://{host}/naver -> naver.com 접속하기

http://{host}/google -> google.com 접속하기

 

절차

1. spring project 구성하기

2. application.yml 설정 구성하기

3. test

 

1. spring project 구성하기

스프링 프로젝트에 spring cloud gateway 의존성을 추가한다.

implementation 'org.springframework.cloud:spring-cloud-starter-gateway'

 

2. application.yml 설정 구성하기

Predicate에 Path를 이용하고 Filter는 naver와 google에는 /naver, /google 같은 path가 없기 때문에 제가해주기 위해서 RewitePath 필터를 사용하는 것을 구성한다.

server:
  port: 80

spring:
  cloud:
    gateway:
      routes:
        - id: naver
          uri: https://www.naver.com
          predicates:
            - Path=/naver/**
          filters:
            - RewritePath=/naver/?(?<segment>.*), /$\{segment}

        - id: google
          uri: https://www.google.com
          predicates:
            - Path=/google/**
          filters:
            - RewritePath=/google/?(?<segment>.*), /$\{segment}

 

3. test

서버 가동이후에 http://localhost/naver 와 http://localhost/google 에 접속하여 정상적으로 접속하는지 확인한다.

 

참고

 

Spring Cloud Gateway

This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 6, Spring Boot 3 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them

docs.spring.io

 

 

SPRING CLOUD GATEWAY를 이용한 API GATEWAY 구축기

안녕하세요. 사람인에이치알 서비스인프라개발팀 이현규 입니다. 이번 포스팅은 현재 사람인에이치알에 구축되어 운영되고 있는 API GATEWAY에 대하여 공유하는 내용의 포스팅입니다. API GATEWAY란?

saramin.github.io

 

 

Getting Started | Building a Gateway

As a good developer, we should write some tests to make sure our Gateway is doing what we expect it should. In most cases, we want to limit our dependencies on outside resources, especially in unit tests, so we should not depend on HTTPBin. One solution to

spring.io