기술나눔

[스프링 클라우드 엘리트 가이드] 심층 탐구와 실전: 게이트웨이의 고급 애플리케이션과 모범 사례

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. 소개

Spring Cloud Gateway는 Spring 5, Spring Boot 2 및 Project Reactor를 포함하여 Spring 에코시스템 위에 구축된 API 게이트웨이를 제공합니다. Spring Cloud Gateway는 간단하면서도 효율적인 라우팅 방법을 제공하고 보안, 모니터링/메트릭 및 복원성과 같은 일부 게이트웨이 기본 기능을 제공하는 것을 목표로 합니다.

아래에서는 두 가지 예를 들어 설명합니다.

2. 릴리스 노트

스프링 부트 버전: 2.2.5.RELEASE

스프링 클라우드 버전: Hoxton.SR3

별도로 지정하지 않는 한 모든 Spring Cloud 루틴은 위 버전을 사용합니다.

3. 게이트웨이 이용

권장사항: 이 강좌를 시작하기 전에 Eureka 생성의 세부 단계를 이해하지 못한다면 [Spring Cloud의 등록센터 Eureka를 예시로 활용하는 방법을 알아보세요],아직 보지 않았더라도 상관없습니다. 시작하려면 아래 단계를 따르세요.

3.1 새 상위 프로젝트 만들기

상위 프로젝트가 없는 경우(등록 센터 인스턴스를 완료한 경우 상위 프로젝트가 있어야 함) 간단한 Maven을 사용하여 상위 프로젝트를 생성하세요.

생성 후 pom.xml 파일을 열고 다음 코드를 추가합니다.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>org.cherry</groupId>
  7. <artifactId>springcloudproject</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  11. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  12. <java.version>14</java.version>
  13. <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
  14. <springboot.version>2.2.5.RELEASE</springboot.version>
  15. </properties>
  16. <dependencyManagement>
  17. <dependencies>
  18. <dependency>
  19. <groupId>org.springframework.cloud</groupId>
  20. <artifactId>spring-cloud-dependencies</artifactId>
  21. <version>${spring-cloud.version}</version>
  22. <type>pom</type>
  23. <scope>import</scope>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-dependencies</artifactId>
  28. <version>${springboot.version}</version>
  29. <type>pom</type>
  30. <scope>import</scope>
  31. </dependency>
  32. </dependencies>
  33. </dependencyManagement>
  34. </project>

src 폴더 삭제

3.2 게이트웨이 하위 프로젝트 만들기

상위 프로젝트에서 Spring 초기화를 사용하여 새 게이트웨이 하위 프로젝트인 게이트웨이를 생성하고 게이트웨이에 의존하도록 선택합니다. 간단한 맵은 다음과 같습니다.

빌드 후 pom.xml 파일을 수정하면 다음과 같습니다.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <artifactId>springcloudproject</artifactId>
  7. <groupId>com.cherry</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. <!-- <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-parent</artifactId>
  11. <version>2.2.6.RELEASE</version>
  12. <relativePath/> &lt;!&ndash; lookup parent from repository &ndash;&gt;-->
  13. </parent>
  14. <groupId>com.cherry</groupId>
  15. <artifactId>gateway</artifactId>
  16. <version>0.0.1-SNAPSHOT</version>
  17. <name>gateway</name>
  18. <description>Demo project for Spring Boot</description>
  19. <!--<properties>
  20. <java.version>1.8</java.version>
  21. <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
  22. </properties>-->
  23. <dependencies>
  24. <dependency>
  25. <groupId>org.springframework.cloud</groupId>
  26. <artifactId>spring-cloud-starter-gateway</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-test</artifactId>
  31. <scope>test</scope>
  32. <exclusions>
  33. <exclusion>
  34. <groupId>org.junit.vintage</groupId>
  35. <artifactId>junit-vintage-engine</artifactId>
  36. </exclusion>
  37. </exclusions>
  38. </dependency>
  39. </dependencies>
  40. <dependencyManagement>
  41. <dependencies>
  42. <dependency>
  43. <groupId>org.springframework.cloud</groupId>
  44. <artifactId>spring-cloud-dependencies</artifactId>
  45. <version>${spring-cloud.version}</version>
  46. <type>pom</type>
  47. <scope>import</scope>
  48. </dependency>
  49. </dependencies>
  50. </dependencyManagement>
  51. <build>
  52. <plugins>
  53. <plugin>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-maven-plugin</artifactId>
  56. </plugin>
  57. </plugins>
  58. </build>
  59. </project>

구성 파일 application.properties를 yml 접미사로 수정(즉, 파일 이름을 application.yml로 변경)하여 게이트웨이를 구성합니다.

여기서는 csdn 블로그를 서비스 공급자로 사용합니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833

실행 실행, springboot 내장 Tomcat 시작, 포트 9001

브라우저 입력 주소http://localhost:9001/huanzi833

3.3 게이트웨이 닫기

게이트웨이를 사용할 수 없도록 하려면 application.yml에 다음 설정을 추가할 수 있습니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. enabled: false

브라우저 접속 결과는 다음과 같습니다.

4. 시간별 라우팅 규칙 일치

참고: 속성 파일을 수정한 후에는 직접 애플리케이션을 다시 시작하세요. 매번 지침을 반복하지는 않습니다.

4.1 경로 매칭 후 시간

라우팅은 After에서 설정한 시간 이후에 적용됩니다. 예: 2020년 1월 1일 이후의 요청은 내 블로그로 전달되며, 이 시간 이전의 요청은 전달할 수 없습니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. - After=2020-01-01T00:00:00+08:00[Asia/Shanghai]
  14. enabled: true

4.2 라우팅 일치까지의 시간

Before에서 설정한 시간 이전의 라우팅이 적용됩니다. 예: 2021년 1월 1일 이전의 요청은 내 블로그로 전달되고, 이 시간 이후의 요청은 전달할 수 없습니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. - After=2020-01-01T00:00:00+08:00[Asia/Shanghai]
  14. - Before=Before=2021-01-01T00:00:00+08:00[Asia/Shanghai]
  15. enabled: true

4.3 경로 매칭 간 시간

Between에서 설정한 시간 사이의 라우팅이 적용됩니다. 예: 2020년 1월 1일부터 2020년 10월 1일 사이의 요청은 내 블로그로 전달됩니다. 이 시간 이외의 요청은 일반적으로 Between 및 After Before를 사용할 수 없습니다. 반복되는 설정을 피하기 위해 함께 사용하세요.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. # - After=2019-01-01T00:00:00+08:00[Asia/Shanghai]
  14. # - Before=2021-01-01T00:00:00+08:00[Asia/Shanghai]
  15. - Between=2020-01-01T00:00:00+08:00[Asia/Shanghai], 2020-10-01T00:00:00+08:00[Asia/Shanghai]
  16. enabled: true

4.4 쿠키 경로 매칭

쿠키의 경우 조건자는 두 개의 매개변수를 받을 수 있습니다. 하나는 쿠키 이름이고 다른 하나는 정규식입니다. 라우팅 규칙은 해당 쿠키 이름 값과 일치하며 일치하는 항목이 없으면 라우팅이 실행됩니다. 라우팅이 실행되지 않습니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. # - After=2019-01-01T00:00:00+08:00[Asia/Shanghai]
  14. # - Before=2021-01-01T00:00:00+08:00[Asia/Shanghai]
  15. - Between=2020-01-01T00:00:00+08:00[Asia/Shanghai], 2020-10-01T00:00:00+08:00[Asia/Shanghai]
  16. - Cookie=uid, cherry #通过cookie进行路由规则的匹配
  17. enabled: true

쿠키 라우팅 일치를 사용하면 cmd를 입력하여 테스트하고 cmd에 다음 명령문을 입력할 수 있습니다.

4.5 헤더 경로 매칭

쿠키 경로 일치와 유사하게 매개변수 이름과 정규식이라는 두 가지 매개변수가 있으며, 일치하는 항목이 있으면 경로가 실행되지 않습니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. # - After=2019-01-01T00:00:00+08:00[Asia/Shanghai]
  14. # - Before=2021-01-01T00:00:00+08:00[Asia/Shanghai]
  15. - Between=2020-01-01T00:00:00+08:00[Asia/Shanghai], 2020-10-01T00:00:00+08:00[Asia/Shanghai]
  16. - Cookie=uid, cherry #通过cookie进行路由规则的匹配
  17. - Header=X-Request-Id, d+ #Header路由规则
  18. enabled: true

테스트하려면 cmd를 입력하고 cmd에 다음 명령문을 입력하십시오.

4.6 호스트 경로 매칭

다음 구성은 www.csdn.net, www.baidu.com, blog.csdn.net 및 기타 주소와 같은 호스트 주소와 일치합니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. # - After=2019-01-01T00:00:00+08:00[Asia/Shanghai]
  14. # - Before=2021-01-01T00:00:00+08:00[Asia/Shanghai]
  15. - Between=2020-01-01T00:00:00+08:00[Asia/Shanghai], 2020-10-01T00:00:00+08:00[Asia/Shanghai]
  16. - Cookie=uid, cherry #通过cookie进行路由规则的匹配
  17. - Header=X-Request-Id, d+ #Header路由规则
  18. - Host=**.csdn.net, **.baidu.com #Host路由规则
  19. enabled: true

테스트하려면 cmd를 입력하고 cmd에 다음 명령문을 입력하십시오.

4.7 경로 매칭 방법

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. # - After=2019-01-01T00:00:00+08:00[Asia/Shanghai]
  14. # - Before=2021-01-01T00:00:00+08:00[Asia/Shanghai]
  15. - Between=2020-01-01T00:00:00+08:00[Asia/Shanghai], 2020-10-01T00:00:00+08:00[Asia/Shanghai]
  16. - Cookie=uid, cherry #通过cookie进行路由规则的匹配
  17. - Header=X-Request-Id, d+ #Header路由规则
  18. - Host=**.csdn.net, **.baidu.com #Host路由规则
  19. - Method=GET, POST #Method路由规则
  20. enabled: true

cmd를 입력하여 Get 테스트를 수행합니다. cmd에 다음 문을 입력합니다.

POST 테스트를 수행하려면 cmd를 입력합니다. cmd에 다음 명령문을 입력합니다. (참고: 서비스 공급자 컨트롤러의 경로가 GetMapping을 사용하고 호출 시 여기서 -X POST를 사용하는 경우 404가 나타납니다.)

4.8 IP 주소 매칭

predicate는 192.168.1.1/24(192.168.1.1은 IP 주소, 24는 서브넷 마스크, 여기서 24는 서브넷 마스크가 255.255.255.0임을 의미)와 같은 특정 IP 간격 번호로 요청을 설정하여 라우팅도 지원합니다. ). 테스트를 위해 이 주소를 로컬 IP 주소로 설정할 수 있습니다.

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. - id: gateway-service
  10. uri: https://blog.csdn.net
  11. predicates:
  12. - Path=/huanzi833
  13. # - After=2019-01-01T00:00:00+08:00[Asia/Shanghai]
  14. # - Before=2021-01-01T00:00:00+08:00[Asia/Shanghai]
  15. - Between=2020-01-01T00:00:00+08:00[Asia/Shanghai], 2020-10-01T00:00:00+08:00[Asia/Shanghai]
  16. - Cookie=uid, cherry #通过cookie进行路由规则的匹配
  17. - Header=X-Request-Id, d+ #Header路由规则
  18. - Host=**.csdn.net, **.baidu.com #Host路由规则
  19. - Method=GET, POST #Method路由规则
  20. - RemoteAddr=192.168.1.1/24
  21. enabled: true

경로 경로 매칭/파라미터 매칭/가중치 매칭은 아래 등록센터와의 통합으로 완료됩니다.

5. 게이트웨이를 서비스로 만들고 이를 등록 센터, 서비스 제공자 및 소비자와 연결합니다.

1. 먼저 유레카 서비스 센터를 생성합니다. 코드는 다음과 같습니다.