MSA - Spring Cloud Gateway
지난 MSA블로그에서 구성 중 유레카 서버와 설정 서버를 만들었다.
- (유레카) https://neunggu.tistory.com/16
- (설정서버) https://neunggu.tistory.com/18
이번에는 게이트 웨이를 만들어 유레카와 설정서버를 연결한다.
코드는 깃허브에 있다. (https://github.com/neunggu/msa-gateway)
GitHub - neunggu/msa-gateway
Contribute to neunggu/msa-gateway development by creating an account on GitHub.
github.com
1. build.gradle에 dependency 추가
dependencies {
// 설정 서버
implementation 'org.springframework.cloud:spring-cloud-config-server'
// 유레카 클라이언트
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
// 게이트웨이
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
...
}
2. 유레카 서버와 설정 서버 연결
이전 블로그 참고.
(유레카) https://neunggu.tistory.com/16
MSA - Spring Cloud Eureka server
스프링 부트에서는 유레카 서버를 아주 간단히 만들 수 있다. 코드는 깃허브에 있다.(https://github.com/neunggu/msa-eureka) GitHub - neunggu/msa-eureka: eureka server eureka server. Contribute to neunggu/msa-eureka development b
neunggu.tistory.com
(설정서버) https://neunggu.tistory.com/18
MSA - Spring Cloud Config server
지난 MSA 블로그에서는 유레카 간단히 유레카 서버를 만들었다. (https://neunggu.tistory.com/16) MSA - Spring Cloud Eureka server 스프링 부트에서는 유레카 서버를 아주 간단히 만들 수 있다. 코드는 깃허브에
neunggu.tistory.com
3. 게이트 웨이 설정
마찬가지로 설정 서버와 연결된 장소에 둔다.(config repository)
https://github.com/neunggu/msa-config-repo/blob/main/gateway-local.yaml
spring:
cloud:
gateway:
default-filters:
- name: GlobalFilter
args:
baseMessage: msa
preLogger: true
postLogger: true
routes:
- id: user-service
uri: http://localhost:1234
predicates:
- Path=/user/**
filters:
- RewritePath=/user/(?<segment>.*), /$\{segment}
# - name: UserFilter
# args:
# baseMessage: user
# preLogger: true
# postLogger: true
- id: wallet-service
uri: http://localhost:1235
predicates:
- Path=/wallet/**
filters:
- RewritePath=/wallet/(?<segment>.*), /$\{segment}
# - name: WalletFilter
# args:
# baseMessage: wallet
# preLogger: true
# postLogger: true
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
gateway:
enabled: true
라우트 마다 연결할 서버와 필터를 추가하고 글로벌 필터도 적용시킬 수 있다.
(게이트 웨이의 추가적인 기능에 대한 부분은 다음에..)
게이트 웨이의 주소에 predicates의 설정한 경로를 붙이면 해당 서버로 연결된다.
ex)
http://localhost:8002/user/... => user-service 호출
http://localhost:8002/wallet/... => wallet-service 호출
4. 게이트 웨이 필터 작성
AbstractGatewayFilterFactory를 상속받아 작성한다.
@Component
public class GlobalFilter extends AbstractGatewayFilterFactory<Config> {
public GlobalFilter() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
log.info("GlobalFilter baseMessage: {}", config.getBaseMessage());
if (config.isPreLogger()) {
log.info("GlobalFilter Start: {}", exchange.getRequest());
}
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
if (config.isPostLogger()) {
log.info("GlobalFilter End: {}", exchange.getResponse());
}
}));
};
}
}
5. 완료
1. 유레카 서버 시작
2. 설정 서버 시작
3. 게이트 웨이 + 나머지 서비스 시작
먼저 필요한 서버부터 순서대로 실행한다.