0Pricing
Spring Boot 4 Microservices & REST APIs · درس

بوابة API باستخدام Spring Cloud Gateway

أعدّ Spring Cloud Gateway لتوجيه الطلبات وتطبيق عوامل التصفية وتأمين خدماتك المصغّرة.

بوابة API باستخدام Spring Cloud Gateway درس مجاني في Spring Boot 4 Microservices & REST APIs على CoddyKit. هذا هو الدرس 3 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Microservices & REST APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why an API Gateway?

Microservices are great for building scalable applications, but they can introduce complexity. Imagine having many services, each with its own address and port.

An API Gateway acts as a single, unified entry point for all client requests. It funnels incoming traffic to the correct microservice, simplifying how clients interact with your backend.

What is Spring Cloud Gateway?

Spring Cloud Gateway (SCG) is a powerful, reactive API Gateway built on Spring Framework 5, Project Reactor, and Spring Boot 2. It's designed for high performance and scalability.

  • It provides flexible routing based on requests.
  • Enables dynamic filtering of requests and responses.
  • Integrates seamlessly with other Spring Cloud projects.

Setting Up Your Gateway Project

To create a Spring Cloud Gateway application, start with a standard Spring Boot project. The key is to add the spring-cloud-starter-gateway dependency.

This dependency pulls in everything needed to transform your Spring Boot app into an intelligent gateway. Remember to include the spring-cloud-dependencies in your dependencyManagement section.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version>
    <relativePath/>
  </parent>
  <groupId>com.coddykit</groupId>
  <artifactId>gateway</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>gateway</name>
  <description>Demo project for Spring Cloud Gateway</description>
  <properties>
    <java.version>17</java.version>
    <spring-cloud.version>2023.0.1</spring-cloud.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>

Defining Basic Routes

Routes are the core of an API Gateway. They tell the gateway how to forward incoming requests to the correct backend service. Routes are defined using predicates and a target URI.

Here, the Path=/hello/** predicate matches any request path starting with /hello/ and routes it to http://localhost:8081.

server:
  port: 8080

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: hello_route
          uri: http://localhost:8081
          predicates:
            - Path=/hello/**

Testing Your Gateway Route

To test the route, you'd typically have a backend microservice running. Let's imagine a simple 'hello-service' running on http://localhost:8081 that responds to any /hello/** path.

  • Start your Gateway application (e.g., on port 8080).
  • Make a request to http://localhost:8080/hello/world.
  • The Gateway intercepts it and forwards it to http://localhost:8081/hello/world.
  • The response from 'hello-service' is then sent back to the client via the Gateway.

Introducing Gateway Filters

Gateway Filters are functions that allow you to modify requests and responses as they pass through the gateway. They are incredibly powerful for implementing cross-cutting concerns.

  • Request Filters: Modify the request before it reaches the target service.
  • Response Filters: Modify the response before it's sent back to the client.

Filters can be applied globally to all routes or specifically to individual routes.

Applying a Simple Filter: AddRequestHeader

Let's enhance our hello_route with a filter. The AddRequestHeader filter is a built-in filter that adds a specified header to the request before forwarding it.

This is useful for injecting correlation IDs, security tokens, or origin information into requests sent to downstream services.

server:
  port: 8080

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: hello_route_with_header
          uri: http://localhost:8081
          predicates:
            - Path=/hello/**
          filters:
            - AddRequestHeader=X-Request-Source, Gateway

Centralizing Security with Gateway

An API Gateway is an ideal place to centralize security mechanisms for your microservices. Instead of implementing authentication and authorization in every service, the gateway can handle it once.

  • Authentication: Validate user credentials or tokens (e.g., JWT).
  • Authorization: Check if the authenticated user has permission for the requested resource.
  • If checks pass, the request proceeds; otherwise, it's rejected at the gateway level.

Beyond Built-in Filters: Custom Filters

While Spring Cloud Gateway provides many useful built-in filters, you might need custom logic. You can create your own filters by implementing the GlobalFilter and Ordered interfaces.

Custom filters are perfect for unique logging requirements, advanced metrics collection, or bespoke security checks that apply across your entire API landscape.

Gateway Concepts Check

Test your understanding of API Gateway fundamentals!

Recap: API Gateway Power

Great job! In this lesson, we explored the crucial role of an API Gateway in a microservices environment, specifically using Spring Cloud Gateway.

  • We understood its purpose as a single entry point.
  • Learned to configure basic routing with predicates.
  • Discovered how filters can modify requests and responses.
  • Touched upon its importance in centralizing security.

API Gateways are essential for building robust, secure, and manageable microservice systems.

الأسئلة الشائعة

هل درس «بوابة API باستخدام Spring Cloud Gateway» مجاني؟

نعم — نص درس «بوابة API باستخدام Spring Cloud Gateway» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Microservices & REST APIs، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.

ماذا ستتعلم في «بوابة API باستخدام Spring Cloud Gateway»؟

أعدّ Spring Cloud Gateway لتوجيه الطلبات وتطبيق عوامل التصفية وتأمين خدماتك المصغّرة. تتمرن على Spring Boot 4 Microservices & REST APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Microservices & REST APIs؟

لا تُشترط خبرة سابقة. Spring Boot 4 Microservices & REST APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 3.

كم من الوقت يستغرق درس «بوابة API باستخدام Spring Cloud Gateway»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Microservices & REST APIs هذا؟

نعم. كل درس في Spring Boot 4 Microservices & REST APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تنفيذ اكتشاف الخدمات باستخدام Eureka
  2. موازنة التحميل من جانب العميل باستخدام Ribbon
  3. بوابة API باستخدام Spring Cloud Gateway
← العودة إلى Spring Boot 4 Microservices & REST APIs