[Spring Boot] Spring Cloud Zuul

Wonjun Seo·2024년 2월 8일
0

Zuul 서버

Zuul 서버는 API Gateway 입니다. 모든 마이크로서비스에 대한 요청을 먼저 받아들이고 라우팅하는 프록시 API Gateway 기능을 수행한다. Zuul은 Edge Service Application으로 동적 라우팅 (Dynamic Routing), 모니터링, 탄력성(확장성), 보안 등의 기능을 제공합니다.

정리하자면 Zuul은 Software Level의 Gateway로 기본적인 라우팅 기능에 필터를 추가해서 위와 같은 모니터링, 보안 등의 기능을 추가할 수 있다.

Spring Cloud Zuul은 Netflix Open Source Project인 Zuul을 Spring Framework에서 동작하도록 만든 것이다.

API Gateway가 필용한 이유

  • 인증/인가: 부적절한 요청을 차단하여 Backend Service를 보호
  • L/B & Routing: Client의 요청에 따라 적절한 Backend Service를 로드밸런싱(L/B: Load Balancing)하고 연결(Routing)
  • Logging: 유통되는 트래픽 로깅
  • Circuit Break: Backend Service 장애 감지 및 대처

Spring Boot에 Zuul 적용

1. pom.xml에 의존성을 추가한다.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2. application.properties에 필요한 정보를 추가한다.

server.port=12400

spring.application.name=spring-zuul

eureka.client.service-url.defaultZone=http://localhost:12300/eureka/
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true

management.endpoints.web.exposure.include=*

zuul.routes.springui.path=/api/**
zuul.routes.springui.service-id=spring-api

이 API Gateway가 받는 요청의 path가 /api/** 형식이라면 spring-api라는 이름을 갖는 마이크로서비스에 요청을 넘기도록 설정하였다.


3. ZuulFilter를 상속하는 클래스를 만들고 Config 파일에 Bean으로 등록한다.

public class CustomZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

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

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

    @Override
    public Object run() throws ZuulException {
        return null;
    }

}

4. Application.java에 @EnableZuulServer@EnableDiscoveryClient를 추가한다.

@SpringBootApplication
@EnableZuulServer
@EnableDiscoveryClient
public class SpringZuulApplication {

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

}

0개의 댓글