API Gateway Service 실습(1)

배지원·2024년 5월 23일

MSA

목록 보기
6/12

2개의 서비스 구현

우선 Gateway를 통해 서버를 분류시키기 위해서는 2개이상의 서버가 존재해야한다. 따라서 2개의 서비스를 만들어 보겠다.

1. First-Service

(1) Gradle File

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
  • eureka-client Dependecy 추가

(2) yml File

server:
  port: 8081

spring:
  application:
    name: my-first-service

eureka:
  client:
    fetch-registry: false
    register-with-eureka: false
  • First-service의 포트번호는 8081로 지정

  • fetch-registry: false:
    => 기본적으로 Eureka 클라이언트는 Eureka 서버로부터 등록된 서비스 인스턴스의 목록을 주기적으로 가져옵니다(패치).
    fetch-registry를 false로 설정하면 이 클라이언트는 Eureka 서버로부터 서비스 인스턴스 목록을 가져오지 않습니다. 즉, 이 클라이언트는 다른 서비스 인스턴스 정보를 알 필요가 없거나, 단순히 자신만의 기능을 수행하는 경우에 사용됩니다.

  • register-with-eureka: false:
    => 기본적으로 Eureka 클라이언트는 자신을 Eureka 서버에 등록하여 다른 서비스가 이 클라이언트를 찾을 수 있도록 합니다.
    register-with-eureka를 false로 설정하면 이 클라이언트는 Eureka 서버에 자신을 등록하지 않습니다. 이는 서비스 디스커버리가 필요 없는 클라이언트나, 단순히 Eureka 서버와 통신하지 않아야 하는 경우에 사용됩니다.

(3) Controller File

@RestController
@RequestMapping("/first-service/")
@Slf4j
public class FirstServiceController {
    @GetMapping("/welcome")
    public String welcome() {
        return "Welcome to First Service";
    }

    @GetMapping("/message")
    public String message(@RequestHeader("first-request") String header){
        log.info(header);
        return "Hello World int First Service";
    }
}

2. Second-Service

(1) Gradle File

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

(2) yml File

server:
  port: 8082

spring:
  application:
    name: my-second-service

eureka:
  client:
    fetch-registry: false
    register-with-eureka: false

(3) Controller File

@RestController
@RequestMapping("/second-service/")
@Slf4j
public class SecondServiceController {
    @GetMapping("/welcome")
    public String welcome() {
        return "Welcome to Second Service";
    }

    @GetMapping("/message")
    public String message(@RequestHeader("second-request") String header){
        log.info(header);
        return "Hello World int Second Service";
    }
}

3. Gateway

(1) Gradle

    implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
  • Reactive Gateway 추가
    => 일반 Gateway말고 Reactive Gateway를 추가해줘야 Tomcat말고 Netty 환경에서 실행 가능
  • eureka-client 추가

(2) yml

server:
  port: 8000

# eureka 설정
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:8761/eureka

# gateway 설정
spring:
  application:
    name: SpringCloudGateway
  cloud:
    gateway:
      routes:
        - id: first-service
          uri: http://localhost:8081/
          predicates:
            - Path=/first-service/**
        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**
  • gateway설정에서 현재 연결시켜줄 서버의 주소를 작성해 준다.

    id : 해당 서버의 이름 first-service
    uri : 해당 서버의 포트번호
    predicates : 조건으로 해당 경로가 입력되면 위의 서버 포트번호로 이동시킴

동작 방식

  1. http://localhost:8000/first-service/message 형식으로 주소 입력
  2. first-service로 시작하기 때문에 Gateway에서 first-service서버로 연결 시켜줌
  3. 따라서, http://localhost:8000/first-service/** 가 입력이 되면 /message의 api 주소에 해당하는 first-service의 Controller 내용이 출력이 되어 "Hello World int First Service" 해당 값이 출력됩니다.
  4. 만약, http://localhost:8000/second-service/message 입력시 second-service의 Controller 내용이 출력이 되기 때문에 "Hello World int Second Service" 해당 값이 출력됩니다.


Reference

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

profile
Web Developer

0개의 댓글