본문 바로가기
Spring Cloud&MSA

(Spring Boot / Spring Cloud / MSA) 4. Zuul이란? / 적용방법

by Developer RyanKim 2019. 2. 7.

Zuul 이란?


모든 마이크로서비스에 대한 요청을 먼저 받아들이고 라우팅하는 프록시 API Gateway 기능을 수행한다.



Spring Cloud의 적용 과정 : Zuul

 

Eureka의 설정이 완료 되었으면 Zuul을 적용해 보자. 먼저 API Gateway로 사용될 프로젝트를 생성하고 설정을 진행해야 한다.

 

1.    Spring Boot 프로젝트를 하나 생성하고 bulid.gradle 파일에 Dependency를 추가한다.

 

 

dependencies {     // Add Zuul Dependency


compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul)

compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')

}

l  Zuul 또한 Eureka Client임을 잊지 말자.

 

2.      application.yml 파일에 Zuul설정에 필요한 정보를 추가한다.

 

# -- Default spring configuration
spring:   application:     name: api-gateway-service
# -- Eureka client eureka:   client:     serviceUrl:       defaultZone: ${EUREKA_URL:http://127.0.0.1:8787/eurek

# -- Zuul

zuul:

routes:

user-service:

path: /user/**

service-id: USER-SERVICE

 

l  라우팅에 관한 설정들을 zuul.routes 밑에 추가한다.

l  Api gateway 받는 요청의 path /user/** 형식이라면 USER-SERVICE 라는 이름을 갖는 마이크로서비스에 요청을 넘기도록 설정하였다.

3.      Application.java 파일의 Class @EnableZuulProxy @EnableDiscoveryClient 추가한다.

 

@EnableZuulProxy

@EnableDiscoveryClient @SpringBootApplication

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

 

 

설정이 완료되면 해당 프로젝트는 Zuul 프록시 역할을 하게된다. 이제 Zuul의 기능을 활용 해 볼 차례다. 나는 이 기능을 활용하기 위해 UI Service에서 User Service API 호출이 일어 날 때 요청이 직접적으로 User Service에 가는 것이 아니라 Api gateway를 거쳐 가도록 코드를 수정할 것이다.

 

@Autowired @Qualifier("overnodesRestTemplate")
private RestTemplate restTemplate;
private
String apiGatewayServiceName= "API-GATEWAY-SERVICE";
private
String apiPath = "/user/get-path";
public
JsonObject get(){
 
return restTemplate.getForEntity("http://" + apiGatewayService + apiPath, JsonObject.class).getBody();
}

 

호출하는 경로가 User Service에서 Api Gateway로 바뀐 것을 볼 수 있다. 그리고apiPath 앞에 /user 라는 path가 추가되었다.  이렇게 다른 마이크로서비스로 요청하는 모든 부분의 경로를 Api Gateway로 수정하고 호출 경로에 /user등 이름으로 구분할 수 있도록 키워드가 추가될 것이다.

 

이 과정에서 우리팀이 고민했던 부분은 Spring security oauth2가 적용되어있기 때문에 UI Service에서 User Service쪽으로 Api Call이 일어날 때 OAuth2RestTemplate을 사용하여 Token값을 함께 넘기고 인증이 된 경우에만 호출이 정상적으로 이루어진다는 것이었다


Api Gateway를 거쳐 갔을 때 Token이 유지되고 인증이 정삭적으로 동작하는지 확인이 필요하였고 Api Gateway쪽과 호출되는 마이크로서비스쪽의 Spring security설정에서 해당 경로만 열어준다면 정상적으로 동작하는 것을 확인하였다.

 

하지만 이렇게 단순히 Token을 넘기기만하는 형태로 Api Gateway를 사용한다면 존재의 의미가 떨어진다. 모든 요청에 대한 Token 검증을 Api Gateway에서 끝내고 호출되는 마이크로서비스에서는 인증에 대한 부분은 아예 신경쓰지 않도록 구성하는 것이 바람직할 것이다.


따라서 우리팀은 Api Gateway Service에 필터를 추가하여 Token에 대한 검증을 모두 마치고 요청이 넘겨지도록 수정할 예정이다.




이상으로 Spring Cloud 적용기를 마칩니다! 읽어주셔서 감사합니다.


By Ryan Kim

댓글