SpringBoot/SpringCloud
[springCloud] Spring Cloud Gateway
유쾌한고등어
2023. 4. 7. 13:24
Spring Cloud Gateway
- 사용자의 요청을 받아 적절한 마이크로 서비스에 라우팅해주는 서버
- Tomcat 이 아닌 비동기식 WAS Netty를 이용한다.
Reverse Proxy
- 클라이언트의 요청을 받고 이 요청을 적절한 Backend 서버로 라우팅 해주는 서버이다.
- 단순라우팅 외에도 기초적인 보안 설정,모니터링을 수행 할 수 있다.
- 리버스 프록시 예로 NginX가 있다.
간단하게 Spring Cloud Gateway를 구현해보자!
먼저, lombok,gateway,Eureka Discovery Client Dependency 를 추가하여 gateway 프로젝트를 생성한다.
- properties를 yml로 바꾸고 아래와 같이설정해준다.
- 유레카에 등록하고, 설정 정보를 적어준다.
- uri는 포워딩될 곳의 주소를적는다.
predicates는 사용자가 입력할 url path 정보 조건을 적는다.
입력한 predicates대로 주소가 포워딩된다.
server:
port: 8000
eureka: # 유레카에 등록
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: apigateway-service
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/**
- 그 후 연결할 firstService프로젝트의 yml은 다음과같이 설정해준다.
server:
port: 8081
#logging:
# level:
# org.springframework: DEBUG
spring:
application:
name: my-first-service
eureka:
client:
fetch-registry: false
register-with-eureka: false
- 이때, 주소값을 적을때 게이트웨이에서 주소값이 넘어가다보니 재설정을 해주어야한다.아니면 404가 뜨게된다!
- RequestMapping을 // http://localhost:8081/welcome -> // http://localhost:8081/first-service/welcome로 변경!
package com.example.restfulwebservice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
// http://localhost:8081/welcome
// http://localhost:8081/first-service/welcome
@RestController
// @RequestMapping("/")
@RequestMapping("/first-service/")
public class FirstServiceController {
@GetMapping("/welcome")
public String welcome(){
return "Welcome to the First service.";
}
}
결과적으로, 8080에서 first-service연결시 8081포트의 first-service가 잘 뜨게됨을 확인할 수 있다.