본문 바로가기
프로그래밍/SPRING

Zuul API GATEWAY - 초간단 설정

by 애플 로그 2022. 7. 14.
반응형

Zuul API GATEWAY - 초간단 설정

 

Zuul이 뭐야?

Zuul은 Netflix에서 개발한 Gateway 오픈 라이브러리 이다.

 

Gateway 는 뭐야?

zuul lib를 이용하여 Gateway 서버를 만들수 있다. ( proxy 서버라고 표현하기도 함. )

MSA 에서 클라이언트에게 분산된 서비스의 단일 진입점 즉, 이는 일종의 출입문 역할을 하며,  뒷단의 API 서버들에게 라우팅 할수 있다. 또한 보안과 인증, 로깅과 같은 횡단 관심사를 각 서비스 마다 적용하려면  힘이 들기때문에 이를 이용하면

편하게 처리할수 있다.

 

 

일반적으로 ureka 와 함꼐 사용하며 아래 2장의 그림이 본 것중에 제일 잘 정리된거 같아 퍼왔다.

 

이미지 출처 : https://lion-king.tistory.com/13
이미지 출처 : https://enjoy-dev.tistory.com/4

 

Eureka 서버에 등록된 API 서버들

 

 

Ureka 서버에 API 서버들이 많이 등록되어 있다.

각각의 서비스 IP주소, 포트도 다르고, 모두 REST API 기반의 서버인데,

앞단의 Gateway와 같은 하나의 출입구로 보안, 인증처리를 하고 통제할수 없을까??

 

1. dependency 추가

내 상황에 맞는 버전을 선택하면 된다.

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-zuul -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    <version>2.2.10.RELEASE</version>
</dependency>

참고 : https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-zuul

 

2.  Zuul 어플리케이션으로 동작하게 하자

@EnableZuulProxy를 사용하여 zuul을 활성화 한다.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableZuulProxy   // zuul을 활성화 하겠다.
@SpringBootApplication
public class ZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class);
    }
}

 

 

3. application.yml 의 정보 추가

Eureka server 접속한 client들 ( RestApi 서버들 ) 호출가능한 서버가 확인될것이다.

아래와 같은 설정으로 필요한 서비스만 지정할수도 있다.

eureka:
  instance:
    prefer-ip-address: true
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8888/eureka

zuul:
  ignoredServices: '*'    # 모두 허용 안함
  routes:
    product:              
      path: /product/**   # /product 뒤로 붙는 호출은 product 서버로 보냄
    order:                
      path: /order/**     # /order 패턴으로 들어오는 호출은 order 서버로 보냄
      
      # 결과론적으로는 product, order만 부분 허용하고 싶을때 이렇게 설정하면 된다

 

Eureka에 정상적으로 잘 접속 되었고, Zuul이 정상적으로 활성화 되었다면,

http://127.0.0.1:7000/actuator/routes  를 호출하여 호출 리스트를 확인할수 있다.

관련 설정에 대해서는 여기를 참고하자

https://cloud.spring.io/spring-cloud-netflix/multi/multi__router_and_filter_zuul.html

 

8. Router and Filter: Zuul

Routing is an integral part of a microservice architecture. For example, / may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM-based router and server-side load balancer

cloud.spring.io

 

4. filter class 추가

filter의 종료는 4가지가 있으며, filterOrder 메서드의 리턴값으로 넘겨 주면된다.

@Slf4j
@Component
public class PreZuulFilter extends ZuulFilter {

    private final String FILTER_TYPE = "pre";
    private final int FILTER_ORDER = 1;

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public int filterOrder() {
        return FILTER_ORDER;
    }

    @Override
    public String filterType() {
        return FILTER_TYPE;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        String path = requestContext.getRequest().getRequestURI();
        String method = request.getMethod();

        log.info("Request Method : {}", path);
        log.info("Request URL : {}", method);

        if ( 인증 or validate ) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseBody("API Gateway not authorized!!");
            requestContext.getResponse().setHeader("Content-Type", "application/json; charset=utf8");
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }

        return null;
    }
}
  • filterType() : filter의 type으로 "pre", "route", "post", "error" 을 용도에 따라 return 
    • PRE 필터  -  API 서버롤 라우팅 되기전에 수행
    • route 필터  -  요청에 대한 라우팅을 다루는 필터
    • POST Filter  - 라우팅 후에 실행되는 필터
    • ERROR Filter - 에러발생시 실행되는 필터
  • filterOrder() : type안에서 해당 필터가 실행되는 순서
  • shoudFilter() : run method를 실행한다면 true, 실행하지 않아도 된다면 false를 return합니다.
  • run() : 실제 filter의 로직을 담당하는 method

댓글