0Pricing
Spring Boot 4 Complete Guide · บทเรียน

เกตเวย์ API ด้วย Spring Cloud Gateway

สร้างเกตเวย์ API โดยใช้ Spring Cloud Gateway เพื่อกำหนดเส้นทางคำขอ จัดการความปลอดภัย และดูแลข้อกังวลที่เกี่ยวข้องกับหลายส่วนของระบบ

เกตเวย์ API ด้วย Spring Cloud Gateway เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

API Gateway: The Front Door

In a microservices architecture, you often have many small, independent services. How do client applications (like a mobile app or web browser) interact with them?

An API Gateway acts as a single, unified entry point for all client requests. Instead of clients needing to know about and call individual services, they simply communicate with the gateway.

Why Use an API Gateway?

Gateways centralize common functionalities that would otherwise be duplicated across multiple services or handled by clients. This simplifies development and enhances service management. Key benefits include:

  • Request Routing: Directing incoming requests to the correct backend microservice.
  • Security: Handling authentication and authorization at the edge.
  • Rate Limiting: Protecting services from being overwhelmed by too many requests.
  • Monitoring & Logging: Centralized collection of request metrics and logs.
  • Circuit Breaking: Improving resilience against failures in downstream services.

Introducing Spring Cloud Gateway

Spring Cloud Gateway (SCG) is a powerful, reactive API Gateway built on Spring WebFlux. It's designed for high performance and scalability, making it ideal for modern microservices.

SCG replaced the older Netflix Zuul and provides a more modern, non-blocking way to manage API traffic efficiently.

Setting Up Your Gateway Project

To start building an API Gateway, you need a Spring Boot project with specific dependencies. The core ones are:

  • spring-cloud-starter-gateway: Provides the gateway capabilities.
  • spring-boot-starter-webflux: The reactive web framework SCG is built upon.

You can easily generate a project with these dependencies using Spring Initializr.

Code: A Minimal Gateway

This is a minimal Spring Cloud Gateway application. It defines a simple route using Java configuration (an alternative to application.yml) that forwards requests from /hello to httpbin.org/get.

Try running it! Then, open your browser and access http://localhost:8080/hello. You should see a JSON response from httpbin.org.

package com.coddykit.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class GatewayApplication {

  public static void main(String[] args) {
    SpringApplication.run(GatewayApplication.class, args);
  }

  @Bean
  public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
      .route("hello_route", r -> r.path("/hello")
        .uri("http://httpbin.org/get"))
      .build();
  }
}

Configuring Routes with YAML

While Java configuration is useful for programmatic routes, the most common and flexible way to define routes in Spring Cloud Gateway is using application.yml or application.properties.

This allows for externalizing configuration and easier management. Each route consists of an id, a target uri, and predicates to match incoming requests.

Example application.yml snippet:

spring: cloud: gateway: routes: - id: my_service_route uri: http://localhost:8081 predicates: - Path=/api/myservice/** server: port: 8080

Request Predicates: The Matchmakers

Predicates are crucial components of a route. They are conditions that must be met for a route to be applied to an incoming request. They evaluate various aspects of the HTTP request.

Common predicates include:

  • Path=/users/**: Matches requests based on the URI path.
  • Method=GET,POST: Matches specific HTTP methods.
  • Host=*.example.com: Matches requests based on the host header.
  • Header=X-Request-Id, \d+: Matches requests with a specific header and a regex value.

Code: Routing with Path Predicate

Let's configure a route using application.yml that uses the Path predicate to forward requests starting with /backend/** to a service running on port 8081.

Place this in your src/main/resources/application.yml:

spring: cloud: gateway: routes: - id: backend_service_route uri: http://localhost:8081 predicates: - Path=/backend/** application: name: api-gateway server: port: 8080

When you access http://localhost:8080/backend/hello, the gateway will route it to http://localhost:8081/hello.

Gateway Filters: Request & Response Magic

Filters allow you to modify the incoming request or the outgoing response. They can be applied to specific routes (route-specific filters) or to all routes (global filters).

Examples of built-in filters:

  • AddRequestHeader: Adds a header to the request before sending it to the downstream service.
  • AddResponseHeader: Adds a header to the response before sending it back to the client.
  • RateLimiter: Controls the number of requests allowed per unit of time, preventing abuse.

Test Your Gateway Knowledge

Consider a Spring Cloud Gateway application configured with the following route:

spring:
  cloud:
    gateway:
      routes:
        - id: my_product_route
          uri: lb://PRODUCT-SERVICE
          predicates:
            - Path=/products/{segment}
          filters:
            - AddRequestHeader=X-Request-Source, Gateway

Which of the following statements are TRUE about this configuration?

Recap: Gateway Essentials

You've learned about the fundamental role of API Gateways in a microservices architecture and how Spring Cloud Gateway implements this pattern.

  • An API Gateway acts as a single, central entry point for clients.
  • Routes define how incoming requests are mapped to backend services.
  • Predicates are conditions that determine which requests a route applies to.
  • Filters allow you to modify requests or responses, handling cross-cutting concerns like security or rate limiting.

Mastering SCG is key to building robust and scalable microservice systems!

คำถามที่พบบ่อย

บทเรียน “เกตเวย์ API ด้วย Spring Cloud Gateway” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “เกตเวย์ API ด้วย Spring Cloud Gateway” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เกตเวย์ API ด้วย Spring Cloud Gateway”

สร้างเกตเวย์ API โดยใช้ Spring Cloud Gateway เพื่อกำหนดเส้นทางคำขอ จัดการความปลอดภัย และดูแลข้อกังวลที่เกี่ยวข้องกับหลายส่วนของระบบ คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “เกตเวย์ API ด้วย Spring Cloud Gateway” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. หลักการและการออกแบบไมโครเซอร์วิส
  2. การค้นหาและลงทะเบียนบริการ
  3. เกตเวย์ API ด้วย Spring Cloud Gateway
  4. การกำหนดค่ารวมศูนย์ด้วย Spring Cloud Config
← กลับไปที่ Spring Boot 4 Complete Guide