티스토리 뷰
Spring Cloud Gateway와 Eureka를 활용하여 간단하게 API Gateway를 만들어보자.
전체적인 흐름은 위 그림과 같다.
Spring Cloud Gateway가 클라이언트와 서버 사이에 라우팅을 해주는 미들웨어 역할을 하고 있고,
Eureka는 서버(MicroService)들의 정보들을 가지고 있고 헬스체크를 해준다.
예시를 들어보자.
만약 사용자가 Order 서비스를 사용하고자 한다면 아래와 같은 순서로 흘러간다.
- 사용자가 Order 서버에 보낼 요청을 Gateway로 전달
- Gateway는 Eureka로부터 Order 서버 정보 획득
- Gateway가 Order 서버로 요청
이러한 구조를 가지면 다음과 같은 장점들을 가지게된다.
- 모든 요청은 Gateway를 거치기 때문에 인증과 로깅 처리를 쉽게할 수 있다
- 클라이언트가 Gateway 정보만 알고있으면 모든 마이크로서비스들을 사용할 수 있다
- 각각의 마이크로서비스들은 서로의 정보를 몰라도 된다(Eureka가 가지고 있다)
실제코드로 한번 구현해보자.
Eureka
build.gradle에 의존성을 추가해주자.
ext {
set('springCloudVersion', "2021.0.3")
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
유레카 설치 후, 메인 클래스에 @EnableEurekaServer 어노테이션을 추가해준다.
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
application.yml은 아래와 같이 설정했다.
server:
port: 8761
spring:
application:
name: eureka-server #Application 이름
eureka:
client:
fetch-registry: false #eureka server를 registry에 등록할지 여부
register-with-eureka: false #registry에 있는 정보들을 가져올지 여부
# service-url:
# defaultZone: http://localhost:${server.port}/eureka #유레카 서버 포트변경 시
이렇게 하면 Eureka 기본 설정이 끝난다.
서버를 구동시키고 http://localhost:8761로 접속하면 아래와 같이 Eureka Dashboard를 볼 수 있다.
아직은 Eureka 클라이언트들을 등록하지 않아 인스턴스가 없다고 나온다.
그럼 차례대로 클라이언트들을 등록해보자.
Service
스프링부트로 User, Order 서비스를 간단하게 만들자.
Member
build.gradle
plugins {
id 'org.springframework.boot' version '2.7.1'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
ext {
set('springCloudVersion', "2021.0.3")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
//eureka
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
tasks.named('test') {
useJUnitPlatform()
}
메인클래스
유레카 클라이언트들은 @EnableDiscoveryClient 어노테이션을 추가해준다.
@SpringBootApplication
@EnableDiscoveryClient
public class Service1Application {
public static void main(String[] args) {
SpringApplication.run(Service1Application.class, args);
}
}
controller
@RestController
public class MemberController {
@GetMapping("/member")
public String userService() {
return "MEMBER SERVICE!";
}
}
application.yml
server:
port: 8081
---
spring:
application:
name: member-service
#eureka:
# client:
# register-with-eureka: true
# fetch-registry: true
# service-url:
# defaultZone: http://127.0.0.1:8761/eureka #Eureka Server 정보
Eureka 서버가 기본포트이고 같은 주소망에 서버들을 올릴거라면 굳이 밑에 주석친 부분을 안적어줘도 된다.
알아서 Eureka가 찾아준다고한다.
Order
build.gradle은 위 Member와 동일하다.
메인클래스
@SpringBootApplication
@EnableDiscoveryClient
public class Service2Application {
public static void main(String[] args) {
SpringApplication.run(Service2Application.class, args);
}
}
Controller
@RestController
public class OrderController {
@GetMapping("/order")
public String userService() {
return "ORDER SERVICE!";
}
}
application.yml
server:
port: 8082
---
spring:
application:
name: order-service
설정 후 유레카 대시보드에 다시 들어가면 아래와 같이 인스턴스 2개가 추가된 것을 볼 수 있다.
*API Gateway 만들기 #2
'개발 > Spring' 카테고리의 다른 글
[Spring] - 스프링에서 자주보이는 xxxTemplate (0) | 2022.07.20 |
---|---|
[Spring] - API Gateway 만들기 #2 (0) | 2022.07.13 |
[JPA] - JPA 즉시로딩과 지연로딩(FetchType.EAGER or LAZY) (0) | 2022.06.20 |
[Spring] - p6spy 사용하기 (0) | 2022.06.19 |
[Spring] - 테스트 코드에서 롬복 사용하기 (0) | 2022.06.19 |