최대 1 분 소요

이전까지는, user-microservice에 랜덤포트가 적용되어있기 때문에
매번 유레카를 통해 user-microservice의 포트번호를 확인한 뒤에 요청해야했다.

그런데 user-microservice를 게이트웨이 서비스에 등록하게 되면,
할당된 포트에 상관없이 서비스의 name을 통해 접근할 것이기 때문에 훨씬 편하게 작업할 수 있다.

gateway-service 생성

  • Spring Boot: 2.7.4
  • dependencies
    - Gateway, Eureka Discovery Client, Lombok

1) gateway-serviceuser-service route 정보 등록

application.yml

server:
  port: 8000

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8761/eureka

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://USER-SERVICE
          predicates:
            - Path=/user-service/**

2) 게이트웨이에 설정한 포트번호로 user-service 접속

user-service의 컨트롤러에 prefix 지정

UserController.java

@RestController
@RequestMapping("/user-service") // 🌟 gateway를 사용하기 위해서 prefix를 지정한다.
public class UserController {
    ...
}

요청할 엔드포인트에 /user-service 추가

예를 들어, /health-check에 접속하고 싶다면,
http://[IP]:[게이트웨이 포트번호]/user-service/health-check로 접속한다.

이제 API Gateway 서비스를 통해 user-service에 요청할 수 있다.
또한, 하나의 포트 번호(게이트웨이의 포트 번호)로 여러 마이크로 서비스에 요청할 수 있다.



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기