2) Spring Boot API Gateway - 2부 API Gateway 설정
앞에서 유레카서버의 설정과 동작 방식을 간단하게 알아봤는데 이제 유레카 서버에서 관리하는 instance정보를
api gateway에서 어떻게 사용하고 어떻게 사용되는지에 대해 알아본다.
먼저 api gateway 서비스를 하나 생성한다.
1. build.gradle
plugins {
id 'org.springframework.boot' version '2.5.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.msa'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
ext {
set('springCloudVersion', "2020.0.3")
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
test {
useJUnitPlatform()
}
2. application.yml
server:
port: 8080
spring:
application:
name: apigateway-service
cloud:
circuitbreaker:
resilience4j:
enabled: true
gateway:
httpclient:
connect-timeout: 2000
response-timeout: 2s
routes:
- id: auth-service
uri: lb://AUTH-SERVICE
predicates:
- Path=/auth-service/**
filters:
- name: CircuitBreaker
args:
name: testCircuitBreaker
fallbackUri: forward:/fallback/auth-service
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
instance:
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
resilience4j:
circuitbreaker:
configs:
default:
registerHealthIndicator: true # actuator를 통해 circuitbraker 상태를 확인하기 위해 설정
minimumNumberOfCalls: 5 # Circuit Breaker가 에러 비율 또 slow call 비율을 계산하기 전에 요구되는 최소한의 요청 수
failureRateThreshold: 50 # 에러 비율 (퍼센트)로 해당 값 이상으로 에러 발생시 서킷이 Open 된다.
waitDurationInOpenState: 10s # 서킷의 상태가 Open에서 Half-open으로 변경되기 전에 Circuit Breaker가 기다리는 시간
instances:
testCircuitBreaker:
baseConfig: default
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
shutdown:
enabled: true
health:
show-details: always # actuator에서 디테일한 정보들을 확인하기 위해 설정
health:
circuitbreakers:
enabled: true # actuator를 통해 circuitbraker 상태를 확인하기 위해 설정
위 application.yml 파일에는 resilience4j 와 spring actuator 에 대한 설정이 추가 되어 있지만 일단 이부분은 없어도 된다. 나중에 이부분에 대해 추가 테스트 해보자.
여기서 필요한 부분은 아래와 같다.
server:
port: 8080
spring:
application:
name: apigateway-service
cloud:
gateway:
httpclient:
connect-timeout: 2000
response-timeout: 2s
routes:
- id: auth-service
uri: lb://AUTH-SERVICE
predicates:
- Path=/auth-service/**
filters:
- name: CircuitBreaker
args:
name: testCircuitBreaker
fallbackUri: forward:/fallback/auth-service
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
instance:
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
여기까지만 추가하면 api gateway의 route 설정 과 해당 api gateway instance를 유레카 서버에 등록하는것 까지 설정이 된다.
여기까지 하고 유레카 서버와 api gateway 서버를 띄워보자.
정상적으로 api gateway instance가 등록된것을 확인!
이 상태에서 앞에서 만들었던 internal api instance를 두개 띄워보자.
Auth service가 정상적으로 등록된것을 확인!!
이제 api gateway를 이용해서 auth-service 의 api를 호출해 보겠습니다.
앞에서 api gateway는 port 8080으로 실행했기 떄문에. auth service의 /auth-service/login api를 호출해보자.
정상적으로 api가 호출되는것이 확인된다~ 이제 api gateway 의 application.yml에 설정한 lb:AUTH-SERVICE 부분에 대한 설명이다.
lb 는 로드밸런싱을 말하는것이다. 자체적으로 ALB를 지원하고 있기 때문에 유레카에 AUTH-SERVICE 로 등록된 instance들에 대해 로드밸싱을 하게 된다.
아래 테스트 결과를 확인해 보면 두개의 instance에서 각각 로그가 번갈아가면서 찍히는것을 확인 할 수 있다.
위 두개의 53011 , 52991 instance가 각각 호출되는것을 확인 할 수 있다.