跳到主要内容

4 篇博文 含有标签「spring-cloud」

查看所有标签

Microservice - Spring Cloud Gateway

· 阅读需 16 分钟
  1. Introduction
  2. Why We Need API Gateway
  3. Build API Gateway
  4. Setting Up API Gateway
  5. Route Configuration
  6. Security and JWT Authentication
  7. Dockerfile Configuration
  8. Helm Chart Configuration
  9. Project Structure
  10. API Gateway Architecture
  11. Sequence Diagrams
  12. HTTPS Configuration for API Gateway
  13. Difference Between lb:// and http:// Protocols
  14. Conclusion

Introduction​

In a microservices architecture, an API Gateway acts as a single entry point for client requests, routing them to the appropriate microservices within the Kubernetes cluster. This article will delve into the setup and configuration of a Spring Cloud API Gateway, focusing on JWT authentication validation, route management, and deployment using Docker and Helm.


Why We Need API Gateway​

Single Entry Point​

An API Gateway provides a single entry point for all client requests, simplifying client-side code and reducing the number of endpoints clients need to interact with.

Routing and Load Balancing​

The gateway routes requests to the appropriate microservices and handles load balancing across multiple instances of each service.

Security​

It centralizes security concerns such as authentication and authorization, reducing the need for each microservice to implement these features independently.

Protocol Translation​

The gateway can handle protocol translation, allowing clients to use a single protocol (e.g., HTTP/2) while communicating with microservices using different protocols.


Build API Gateway​

Is there an official API Gateway image?

  • Currently, Spring Cloud Gateway does not offer an official pre-built Docker image, developers build a Spring Boot application with spring-cloud-starter-gateway and custom configurations (routes, JWT filter, etc.).

  • As gateway services are often customized for specific routing, load balancing, security and potentially other cross-cutting concerns and needs. It acts as the main entry point for all external requests to your microservices. The gateway can either pull routing configurations from a service discovery mechanism(like Spring Cloud Kubernetes Discovery) or have the configurations set explicitly.

Steps to Build a Production-Ready API Gateway

  1. Route Configuration: Define routing rules either in application.yml or using Java annotations.
  2. Security Setup: Add JWT validation (e.g., JwtAuthenticationFilter) and configure security policies in the gateway.
  3. Service Discovery: Use Spring Cloud Kubernetes for service discovery, allowing the gateway to dynamically discover services.
  4. Containerization and Deployment: Build a Docker image and deploy it to Kubernetes with a Helm chart for scalability and configuration management.

Setting Up API Gateway​

Step 1: Add Dependencies​

Add the necessary dependencies to your pom.xml file.

<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>

Step 2: Create the Main Application Class​

Create the main application class for the Spring Cloud Gateway.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Service Discovery and Routing Configuration​

YAML-based Configuration​

Configure routes in the application.yml file.

spring:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true # Ensures lowercase naming for services
routes:
- id: profile_service
uri: lb://profile-svc
predicates:
- Path=/profile/**
- id: inventory_service
uri: lb://inventory-svc
predicates:
- Path=/inventory/**
- id: order_service
uri: lb://order-svc
predicates:
- Path=/order/**
- id: shipment_service
uri: lb://shipment-svc
predicates:
- Path=/shipment/**

kubernetes:
discovery:
all-namespaces: true # Discover services across all namespaces
service-labels: # Optional: filter based on labels
environment: production
  • lb:// */ scheme: Enables load balancing across multiple instances of each microservice.
  • Service Discovery: The gateway will detect microservices like inventory-service or shipment-service using Kubernetes service discovery, eliminating the need for hardcoding service addresses.

Annotation-based Configuration​

Alternatively, configure routes programmatically using annotations.

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayRoutesConfig {

@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("profile_service_route", r -> r.path("/profile/**")
.uri("lb://profile-svc"))
.route("inventory_service_route", r -> r.path("/inventory/**")
.uri("lb://inventory-svc"))
.route("order_service_route", r -> r.path("/order/**")
.uri("lb://order-svc"))
.route("shipment_service_route", r -> r.path("/shipment/**")
.uri("lb://shipment-svc"))
.build();
}
}

Enable Service Discovery To enable service discovery, you can use the @EnableDiscoveryClient annotation. This annotation is typically placed in a configuration class.

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableDiscoveryClient
public class DiscoveryConfig {
// Additional configuration for service discovery can be added here if needed
}

application.yml Configuration for Service Discovery​

Ensure that the following configuration is present in your application.yml or application.properties file to enable service discovery and other settings:

spring:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
kubernetes:
discovery:
all-namespaces: true
service-labels:
environment: production

Summary​

  • Annotation-based Configuration: The GatewayRoutesConfig class defines the routes using the RouteLocatorBuilder.
  • Service Discovery: The DiscoveryConfig class enables service discovery using the @EnableDiscoveryClient annotation.
  • YAML Configuration: The application.yml file contains the necessary settings for service discovery and gateway configuration.

Note: The discovery settings, such as enabling discovery locator and configuring Kubernetes discovery, cannot be directly configured using annotations in the configuration class. These settings are typically configured in the application.yml or application.properties file.


Security and JWT Authentication​

Add Dependencies Include spring-boot-starter-oauth2-resource-server and spring-cloud-starter-gateway in your pom.xml:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>

Gateway Application Properties Configuration: Configure application.yml for JWT validation. This includes specifying the JWT issuer URI and enabling authorization.

spring:
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: inventory-service
uri: lb://inventory-service
predicates:
- Path=/inventory/**
filters:
- TokenRelay # Forward the token to the downstream services
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://<your-auth-provider>/realms/your-realm
  • TokenRelay Filter: Passes the JWT token along with requests to the backend services.
  • Issuer URI: This points to your authentication provider, e.g., an OpenID Connect provider like Keycloak or Auth0.

Enable JWT Authentication: Set up SecurityConfig to enable JWT authentication and configure routes for authorized access.

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange()
.pathMatchers("/inventory/**", "/shipment/**").authenticated() // Require auth for specified paths
.anyExchange().permitAll()
.and()
.oauth2ResourceServer()
.jwt(); // Enable JWT authentication

return http.build();
}
}
  • This configuration restricts access to /inventory/** and /shipment/** endpoints to authenticated users, while allowing others as specified.

Annotation-based Configuration for Routes and Filters

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
public class GatewayRoutesConfig {

@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("inventory-service", r -> r.path("/inventory/**")
.filters(f -> f.filter(new JwtAuthenticationFilter("ROLE_USER,ROLE_ADMIN")))
.uri("lb://inventory-service"))
.build();
}

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwkSetUri("https://example-issuer.com/.well-known/jwks.json")
.and()
.and()
.csrf().disable();
return http.build();
}
}

>**Note**: **Annotation-based Configuration**: The `GatewayRoutesConfig` class defines the routes and filters using the `RouteLocatorBuilder`. It also configures security settings using Spring Security annotations.

JWT Authentication Filter​

Create a JWT authentication filter to verify incoming requests.

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;

@Configuration
public class SecurityConfig {

@Autowired
private JwtDecoder jwtDecoder;

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
AuthenticationWebFilter jwtAuthFilter = new AuthenticationWebFilter(authenticationManager());
http
.authorizeExchange()
.pathMatchers("/oauth2/**").permitAll()
.pathMatchers("/inventory/**", "/shipment/**").authenticated().permitAll()
.anyExchange().authenticated()
.and().addFilterAt(jwtAuthFilter, SecurityWebFiltersOrder.AUTHENTICATION);

return http.build();
}

@Bean
public AuthenticationManager authenticationManager() {
return new JwtAuthenticationManager(jwtDecoder);
}
}

JWT Decoder Configuration​

Configure the JWT decoder to validate tokens.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

@Configuration
public class JwtConfig {

@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(publicKey).build();
}
}

Service-to-Service Communication via Gateway​

To communicate between services, such as shipment-service needing to communicate with inventory-service, microservices can send requests through the API Gateway.

This method simplifies routing, as services only need to know the gateway address and the service paths (e.g., /inventory/**). This approach enhances security and centralizes cross-cutting concerns like authentication, logging, and rate limiting.

Benefits of Gateway-based Communication​

  1. Centralized Security: JWT and other auth mechanisms can be handled at the gateway.
  2. Simplified Routing: Each service interacts with others via a single entry point.
  3. Enhanced Scalability: Kubernetes manages load balancing for each service, and the gateway balances requests across pods.

Service Discovery and Routing Workflow​

[External Client] --> [API Gateway]
|
| (Discovers routes from Kubernetes Discovery)
|
[inventory-service] <--+-- "lb://inventory-service"
[shipment-service] <--+-- "lb://shipment-service"
[other-service] <--+-- Discovered automatically

Sequence Diagram: Inventory and Shipment Communication via Gateway

  1. Shipment Service sends a request to API Gateway at /inventory/items.
  2. API Gateway validates the JWT token, looks up inventory-service route, and forwards the request.
  3. Inventory Service responds with the requested data.
  4. API Gateway relays the response to Shipment Service.
Shipment Service --> API Gateway: Request /inventory/items with JWT
API Gateway --> inventory-service: Validate JWT and route to inventory
inventory-service --> API Gateway: Return data
API Gateway --> Shipment Service: Relay data response

Example: Sending an Authenticated Request to Another Microservice via the Gateway

In shipment-service, use Spring's WebClient to call the inventory-service through the API Gateway.

  1. Define WebClient Bean for Consistency Across Calls

    @Bean
    public WebClient.Builder webClientBuilder() {
    return WebClient.builder();
    }
  2. Send Authenticated Request through Gateway

    @Autowired
    private WebClient.Builder webClientBuilder;

    public InventoryResponse fetchInventoryItems(String token) {
    return webClientBuilder
    .build()
    .get()
    .uri("http://api-gateway/inventory/items")
    .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
    .retrieve()
    .bodyToMono(InventoryResponse.class)
    .block();
    }
    • Token Forwarding: The token is forwarded with the request, allowing the gateway to validate it before routing to the target service.
    • Gateway URI: Requests go through http://api-gateway/inventory/items, routing based on service discovery.

In this example:

  • The gateway is deployed separately in Kubernetes and handles dynamic service discovery and routing via lb:// URIs.
  • Service-to-service calls leverage the API Gateway for ease of scaling, simplified routing, and centralized security. Each service only needs to know the API Gateway’s address and service paths.

Comparison: Gateway vs. Direct Service-to-Service Calls​

AspectAPI Gateway RoutingDirect Service-to-Service Calls
RoutingCentralized, via API GatewayDirect, each service must know other services
JWT ValidationCentralized in GatewayEach service needs to validate tokens
ScalingGateway handles scaling and balancingEach service scales independently
SecurityJWT validated once at the gatewayJWT validation needed in each service
Use CaseBest for external and internal callsIdeal for internal-only, tightly integrated

Dockerfile Configuration​

Create a Dockerfile for building the API Gateway image.

# Start with the base image for Java
FROM openjdk:17-jdk-slim

# Set working directory
WORKDIR /app

# Copy the API Gateway JAR to the image
COPY target/api-gateway.jar api-gateway.jar

# Expose port 8443 for the API Gateway
EXPOSE 8443

# Run the API Gateway application
ENTRYPOINT ["java", "-jar", "api-gateway.jar"]

Build and Push the Docker Image​

docker build -t myregistry/api-gateway:latest .
docker push myregistry/api-gateway:latest

Helm Chart Configuration​

Helm Chart Structure​

api-gateway/
├── Chart.yaml
├── values.yaml
└── templates/
├── deployment.yaml
├── service.yaml
└── ingress.yaml

Chart.yaml​

apiVersion: v2
name: api-gateway
version: 0.1.0
description: API Gateway for Microservices

values.yaml​

image:
repository: myregistry/api-gateway
tag: latest
pullPolicy: IfNotPresent

replicaCount: 2

service:
type: ClusterIP
port: 8443

ingress:
enabled: true
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
hosts:
- host: api.example.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: api-gateway-tls
hosts:
- api.example.com

templates/deployment.yaml​

apiVersion: apps/v1
kind: Deployment
metadata:
name: api-gateway
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app: api-gateway
template:
metadata:
labels:
app: api-gateway
spec:
containers:
- name: api-gateway
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
ports:
- containerPort: 8443

templates/service.yaml​

apiVersion: v1
kind: Service
metadata:
name: api-gateway
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.port }}
targetPort: 8443
selector:
app: api-gateway

templates/ingress.yaml​

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: api-gateway-ingress
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
tls:
- hosts:
- api.example.com
secretName: api-gateway-tls
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: api-gateway
port:
number: 8443

Project Structure​

api-gateway/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── apigateway/
│ │ │ ├── ApiGatewayApplication.java
│ │ │ ├── config/
│ │ │ │ ├── GatewayRoutesConfig.java
│ │ │ │ ├── SecurityConfig.java
│ │ │ │ └── JwtConfig.java
│ │ └── resources/
│ │ └── application.yml
├── Dockerfile
├── pom.xml
└── helm/
└── api-gateway/
├── Chart.yaml
├── values.yaml
└── templates/
├── deployment.yaml
├── service.yaml
└── ingress.yaml

API Gateway Architecture​

graph TD
A[Client] -->|HTTPS| B[API Gateway]
B -->|lb://| C[Profile Service]
B -->|lb://| D[Inventory Service]
B -->|lb://| E[Order Service]
B -->|lb://| F[Shipment Service]
B -->|lb://| G[OAuth2 Service]

Explanation​

  1. Client: Sends requests to the API Gateway over HTTPS.
  2. API Gateway: Routes requests to the appropriate microservice using lb:// protocol.
  3. Microservices: Each service handles requests and returns responses to the API Gateway.

Sequence Diagrams​

Sequence Diagram for Client Request​

sequenceDiagram
participant Client
participant API Gateway
participant Profile Service
participant Inventory Service
participant Order Service
participant Shipment Service

Client->>API Gateway: HTTPS Request
API Gateway->>Profile Service: lb://profile-svc
API Gateway->>Inventory Service: lb://inventory-svc
API Gateway->>Order Service: lb://order-svc
API Gateway->>Shipment Service: lb://shipment-svc
Profile Service-->>API Gateway: Response
Inventory Service-->>API Gateway: Response
Order Service-->>API Gateway: Response
Shipment Service-->>API Gateway: Response
API Gateway-->>Client: HTTPS Response

Sequence Diagram for JWT Authentication​

sequenceDiagram
participant Client
participant API Gateway
participant OAuth2 Service

Client->>API Gateway: HTTPS Request with JWT
API Gateway->>OAuth2 Service: Validate JWT
OAuth2 Service-->>API Gateway: JWT Valid
API Gateway-->>Client: HTTPS Response

HTTPS Configuration for API Gateway​

Step 1: Generate SSL Certificate​

Generate a self-signed SSL certificate or obtain one from a Certificate Authority (CA).

# Generate a self-signed certificate (for testing purposes)
keytool -genkeypair -alias api-gateway -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore api-gateway-keystore.p12 -validity 365

Step 2: Configure HTTPS in application.yml​

Add the keystore settings to application.yml.

server:
port: 8443
ssl:
enabled: true
key-store: classpath:api-gateway-keystore.p12
key-store-password: your_password_here
key-store-type: PKCS12

Step 3: Update Routes to Use lb://​

Ensure that the routes use lb:// to leverage service discovery and load balancing.

spring:
cloud:
gateway:
routes:
- id: profile_service
uri: lb://profile-svc
predicates:
- Path=/profile/**
- id: inventory_service
uri: lb://inventory-svc
predicates:
- Path=/inventory/**
- id: order_service
uri: lb://order-svc
predicates:
- Path=/order/**
- id: shipment_service
uri: lb://shipment-svc
predicates:
- Path=/shipment/**

Step 4: Update Kubernetes Ingress for HTTPS​

Configure the Kubernetes Ingress to redirect traffic to the API Gateway’s HTTPS endpoint.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: api-gateway-ingress
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
tls:
- hosts:
- api.example.com
secretName: api-gateway-tls
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: api-gateway
port:
number: 8443

Difference Between lb:// and http:// Protocols​

lb:// Protocol​

  • Service Discovery: Uses Kubernetes service discovery to find the appropriate service instance.
  • Load Balancing: Automatically load balances requests across multiple instances of the service.
  • Dynamic Routing: Routes can be dynamically updated based on service availability.

Example:

spring:
cloud:
gateway:
routes:
- id: profile_service
uri: lb://profile-svc
predicates:
- Path=/profile/**

http:// Protocol​

  • Direct Routing: Routes requests directly to a specific URL.
  • No Load Balancing: Does not provide load balancing or service discovery.
  • Static Routing: Routes are static and do not change based on service availability.

Example:

spring:
cloud:
gateway:
routes:
- id: profile_service
uri: http://profile-svc:8080
predicates:
- Path=/profile/**

When to Use Each Protocol​

  • Use lb:// for routes within Kubernetes service discovery, allowing the gateway to leverage load balancing.
  • Use http:// for direct routes to a specific URL or when no service discovery is available.

The other option

Here’s a step-by-step setup for building the API Gateway with JWT authentication and routing configurations:

Step 1: Configure API Gateway with JWT Authentication and Routing​

# application.yml
spring:
cloud:
gateway:
routes:
- id: inventory-service
uri: lb://inventory-service
predicates:
- Path=/inventory/**
filters:
- name: JwtAuthenticationFilter
args:
roles: "ROLE_USER,ROLE_ADMIN" # Add roles if role-based access is needed
discovery:
locator:
enabled: true # Enables dynamic route lookup from discovery service
default-filters:
- StripPrefix=1 # Adjusts the path for downstream services

security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://example-issuer.com # Point to the JWT issuer
jwk-set-uri: https://example-issuer.com/.well-known/jwks.json # Set up for validation

Step 2: Implement JWT Authentication Filter for Gateway​

The custom JWT filter ensures each request includes a valid JWT token.

// JwtAuthenticationFilter.java
@Component
public class JwtAuthenticationFilter implements GatewayFilter {

private final JwtDecoder jwtDecoder;

public JwtAuthenticationFilter(JwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String authHeader = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
try {
Jwt jwt = jwtDecoder.decode(token); // Validates the JWT
return chain.filter(exchange); // If valid, proceed with the request
} catch (JwtException e) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}

Add the filter in application.yml for it to be applied to specific routes (like inventory-service in this case).

Step 3: Building and Deploying the API Gateway as a Docker Image​

  1. Dockerfile for the API Gateway:

    # Dockerfile for api-gateway
    FROM openjdk:17-jdk-slim
    ARG JAR_FILE=target/api-gateway.jar
    COPY ${JAR_FILE} api-gateway.jar
    ENTRYPOINT ["java", "-jar", "/api-gateway.jar"]
  2. Build the Docker Image:

    docker build -t myregistry/api-gateway:latest .
    docker push myregistry/api-gateway:latest # Push to your registry
  3. Kubernetes Deployment Configuration:

    # api-gateway-deployment.yaml
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: api-gateway
    labels:
    app: api-gateway
    spec:
    replicas: 2
    selector:
    matchLabels:
    app: api-gateway
    template:
    metadata:
    labels:
    app: api-gateway
    spec:
    containers:
    - name: api-gateway
    image: myregistry/api-gateway:latest
    ports:
    - containerPort: 8080
    env:
    - name: SPRING_PROFILES_ACTIVE
    value: k8s

Step 4: Service-to-Service Communication via Gateway​

Now, other services can call the gateway (using api-gateway service DNS) and append the target service’s route (/inventory/*) to the request path.

Sample Code for a Downstream Service Request Using WebClient with JWT​

// ShipmentService.java
@Service
public class ShipmentService {

private final WebClient webClient;

public ShipmentService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder
.baseUrl("http://api-gateway") // Gateway URL in Kubernetes DNS
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + jwtToken)
.build();
}

public Inventory getInventory(String id) {
return webClient.get()
.uri("/inventory/" + id)
.retrieve()
.bodyToMono(Inventory.class)
.block();
}
}

Comparison: Gateway vs. Interceptor-Based JWT Validation​

AspectGateway with JWT FilterService-Level JWT Interceptors
Centralized ControlAll JWT validation centralized at gatewayEach service has independent JWT validation
Configuration ComplexityEasier for microservices, managed in gatewayMore complex across multiple services
Performance OverheadCan cause bottleneck at gateway if overloadedDistributed load, but duplicate processing
ResilienceSingle point of failure without redundancyMore resilient, distributed across services
Authorization FlexibilityOffers consistent authentication policyEach service can implement role-based restrictions

Microservice meet with Spring Cloud and Kubernetes

· 阅读需 13 分钟

Introduction​

The objective is to design and deploy a group of microservices: Profile Service, Inventory Service, Order Service, Shipment Service, and an OAuth2 Service for centralized authentication. Key requirements include robust service discovery, API Gateway setup, secure communication, and efficient load balancing for high availability and fault tolerance in Kubernetes.

High-Level Architecture​

Each microservice will be deployed in a Kubernetes cluster with multiple replicas, leveraging Spring Cloud Kubernetes Discovery for service registration and Spring Cloud LoadBalancer for client-side load balancing. An API Gateway will handle external requests, providing routing, load balancing, and JWT-based authentication. Communication between services is secured with JWT tokens generated by the OAuth2 Service.

Service Design​

Each microservice is structured independently, deployed as a standalone Spring Boot application with individual responsibilities and access rules. Here’s an overview of the key services:

1. Profile Service​

Manages customer profiles, providing endpoints for CRUD operations on profile data. Accessible to services like Order and Shipment for customer information retrieval.

2. Inventory Service​

Tracks inventory levels and provides endpoints to update, retrieve, and manage inventory data. Called by the Order Service for real-time inventory status updates.

3. Order Service​

Processes customer orders, calculates totals, and interfaces with Inventory and Profile Services. This service is central to the architecture, relying on other services for a smooth customer experience.

4. Shipment Service​

Manages shipment tracking and logistics for orders, called by the Order Service once an order is processed and confirmed.

5. OAuth2 Service​

Acts as the authentication provider, issuing and validating JWT tokens for secure communication. The API Gateway uses these tokens to authenticate requests.

Order-Service Auth-Service Inventory-Service
| | |
|--- Request JWT ------------->| |
| | |
|<-- Receive JWT --------------| |
| | |
|--- Call Inventory ---------->| |
| (with JWT) | |
| |--- Validate JWT------------>|
| | |
| |<-- JWT Valid/Invalid--------|
| | |
|<-- Receive Inventory Data -- | |

Kubernetes Deployment and Service Discovery​

Each service will be deployed to Kubernetes as a Deployment with multiple replicas and exposed via a Service to enable discovery. Spring Cloud Kubernetes is used for service registration and discovery.

Configuring Kubernetes Service Discovery for Each Microservice​

To set up service discovery in Kubernetes, add the following dependencies to your pom.xml:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-discovery</artifactId>
</dependency>

Configure the application.yml in each service to enable discovery:

spring:
cloud:
kubernetes:
discovery:
enabled: true #Enable service discovery
config:
enabled: true
loadbalancer:
enabled: true #Enable loadbalancer

This configuration registers each service with Kubernetes' internal DNS, allowing them to be discoverable by service name within the namespace. This way, each microservice is registered under its own Kubernetes service name, and can resolve other services (e.g., http://inventory-service:8080) when communicating with them. This configuration, combined with Kubernetes DNS, helps maintain an efficient, loosely coupled architecture.

Note: The Kubernetes Service Discovery configuration should indeed be included in each individual microservice’s configuration to ensure they can all register themselves with the Kubernetes DNS and be discoverable by other services in the namespace. This setup allows each microservice to dynamically locate and communicate with other services via Kubernetes' internal DNS naming conventions.

Why Configure Service Discovery in Each Microservice?

Each microservice is an independently deployed unit, so configuring Spring Cloud Kubernetes Discovery in each service's application.yml allows it to:

  1. Register with Kubernetes DNS under a unique service name, enabling internal routing across services.
  2. Access other services by simply using their service names, as Kubernetes DNS provides a consistent way to locate services within the cluster.

Note Here you might be noticed that both the discovery and load balancer components are configured within each microservice. This design allows each microservice to dynamically discover the current instances of other services (using the spring-cloud-kubernetes-discovery integration) and balance requests among those instances using the spring-cloud-loadbalancer component.

Service Registration​

Each microservice is deployed as a separate Deployment and Service in Kubernetes. Here’s an example of the inventory-service Kubernetes configuration:

To deploy and register microservices like an Inventory Service in Kubernetes, we use Spring Cloud’s Kubernetes Discovery capabilities, allowing services to register with Kubernetes’ DNS-based service registry automatically.

Step 1: Create a Kubernetes Service and Deployment for each microservice:

YAML files for defining the service and deployment:

# inventory-service-deployment.yml
apiVersion: v1
kind: Service
metadata:
name: inventory-service
spec:
selector:
app: inventory
ports:
- protocol: TCP
port: 8080
targetPort: 8080
type: ClusterIP # Internal access within the cluster

---
apiVersion: apps/v1
kind: Deployment
metadata:
name: inventory-deployment
spec:
replicas: 2 # Number of instances (pods) of the Inventory Service
selector:
matchLabels:
app: inventory
template:
metadata:
labels:
app: inventory
spec:
containers:
- name: inventory
image: myregistry/inventory-service:latest
ports:
- containerPort: 8080

This configuration deploys inventory-service with two replicas, registered under the service name inventory-service. Other services can communicate with it via http://inventory-service:8080.

More comprehensive explainations When deploying an inventory-deployment with two replicas, you will indeed see two pods running in parallel in the specified namespace. Kubernetes names these pods based on the deployment name, followed by a unique suffix (not just sequential numbers), so you may see pod names like inventory-deployment-abc12 and inventory-deployment-def34.

In Kubernetes, these two pods are managed by a single inventory-service which acts as a layer of abstraction. When the client load balancer targets inventory-service, the service uses Kubernetes' built-in load balancing to forward requests to one of the available inventory-deployment pods.

How Kubernetes Service Load Balancing Works:

  1. Service Abstraction: The inventory-service has a Cluster IP that exposes the service within the cluster.
  2. Endpoints Selection: The service maintains an updated list of active pod IPs (called "endpoints") that match the deployment selector.
  3. Round-Robin Load Balancing: Kubernetes uses a round-robin approach by default. When a request reaches inventory-service, it selects one of the pod IPs associated with the deployment, balancing requests across pods automatically. The service doesn't keep state; each request is independently forwarded to one of the pod replicas.

Example Flow:

  1. Client Request: A client load balancer sends a request to the inventory-service endpoint.
  2. Service to Pod Routing: Kubernetes service routing picks an endpoint (pod IP) from the inventory-deployment pods and forwards the request to it.

For better control and observability, custom load balancer configurations can also be implemented to fine-tune how the requests are distributed, especially in setups requiring sticky sessions or advanced routing.

Step 2: Register Service with Kubernetes Discovery:

Spring Cloud Kubernetes automatically registers inventory-service based on the deployment labels. Enable Spring Cloud Discovery in your Spring Boot application via @EnableDiscoveryClient:

@EnableDiscoveryClient
@SpringBootApplication
public class InventoryServiceApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryServiceApplication.class, args);
}
}

Step 3: Configure Discovery in application.yml:

spring:
cloud:
kubernetes:
discovery:
enabled: true
all-namespaces: true # Optional: enables discovery across namespaces

Load Balancing with Spring Cloud LoadBalancer​

To efficiently distribute incoming requests across available instances, Spring Cloud LoadBalancer provides a client-side load-balancing solution, automatically distributing traffic among instances of a service.

Enable Spring Cloud LoadBalancer by adding Spring Cloud LoadBalancer dependency:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

Configure a ServiceInstanceListSupplier bean for custom load balancing behavior if required:

import org.springframework.cloud.client.loadbalancer.ServiceInstanceListSupplier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LoadBalancerConfig {

@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier() {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withCaching()
.build();
}
}

Set Up Load Balancer with WebClient:

  • Configure a WebClient bean with load balancing to distribute requests among inventory-service instances.
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
}

Use Load-Balanced WebClient in the calling service:

@Service
public class InventoryClient {

private final WebClient.Builder webClientBuilder;

public InventoryClient(WebClient.Builder webClientBuilder) {
this.webClientBuilder = webClientBuilder;
}

public Mono<Product> getProductById(String productId) {
return webClientBuilder.build()
.get()
.uri("http://inventory-service/products/{id}", productId)
.retrieve()
.bodyToMono(Product.class);
}
}

How Load Balancing Works:

  • Spring Cloud LoadBalancer, by default, uses a round-robin strategy to distribute requests.
  • It balances requests between the two inventory-service pods and automatically updates when new instances are added or removed.

  1. By default, Spring Cloud LoadBalancer will round-robin requests to different instances, or customize by implementing a custom LoadBalancerRequestTransformer.

API Gateway Setup​

The Spring Cloud API Gateway is deployed as a separate microservice, managing traffic and providing JWT-based authentication. The gateway routes requests to the appropriate services and load-balances among available replicas.

Routing and Load Balancing​

[External Client] --> [API Gateway]
|
| (Discovers routes from Kubernetes Discovery)
|
[inventory-service] <--+-- "lb://inventory-service"
[shipment-service] <--+-- "lb://shipment-service"
[order-service] <--+-- "lb://order-service"
[profile-service] <--+-- "lb://profile-service"
[other-service] <--+-- Discovered automatically

Configure the gateway’s application.yml to define routes to each service:

spring:
cloud:
gateway:
routes:
- id: profile
uri: http://profile-service
predicates:
- Path=/profile/**
- id: inventory
uri: http://inventory-service
predicates:
- Path=/inventory/**
default-filters:
- TokenRelay

The TokenRelay filter enables the gateway to forward JWT tokens to downstream services for authenticated requests.

Configuring JWT Authentication​

For security, JWT validation can be implemented in the gateway or within each service. Here’s how to configure JWT validation in the gateway:

  1. Add OAuth2 dependencies to the gateway:

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
  2. Configure JWT validation in the gateway’s application.yml:

    spring:
    security:
    oauth2:
    resourceserver:
    jwt:
    issuer-uri: https://auth-server/oauth2/default

Microservice Communication​

Microservices communicate through Spring Cloud LoadBalancer and WebClient.

Using WebClient with Load Balancer​

To call the inventory-service from the order-service, configure WebClient with load balancing:

@Configuration
public class WebClientConfig {

@LoadBalanced
@Bean
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}

Example: Order Service Calls Profile Service​

Here’s how order-service might call profile-service:

@RestController
public class OrderController {

private final WebClient.Builder webClientBuilder;

@Autowired
public OrderController(WebClient.Builder webClientBuilder) {
this.webClientBuilder = webClientBuilder;
}

@GetMapping("/order/{orderId}")
public Mono<OrderDetails> getOrderDetails(@PathVariable String orderId) {
return webClientBuilder.build()
.get()
.uri("http://profile-service/profile/{orderId}", orderId) // The uri can be either http or lb(load balancer)
.retrieve()
.bodyToMono(OrderDetails.class);
}
}

Securing Microservices​

Secure Communication with mTLS and JWT

mTLS (mutual TLS) and JWT (JSON Web Token) are two primary ways to secure communication between microservices.

  • mTLS: Ensures that both the client and server authenticate each other, useful in a zero-trust network.
  • JWT: Adds stateless authentication, where each request includes a signed token with user and session data.

Each microservice validates JWT tokens received from the gateway, ensuring secure and authenticated communication.

JWT Authentication with API Gateway​

JWT Authentication is often managed at the API Gateway, validating tokens and authorizing requests before forwarding them to services.

In this approach, JWT validation is centralized in the gateway. Tokens are verified at the gateway and forwarded to services, reducing the validation load on individual services.

  1. Add Spring Security Dependency for JWT support:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. Configure JWT Verification in Gateway:

Validate JWTs at the gateway level, allowing only authorized requests to reach downstream services.

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and()
.oauth2ResourceServer().jwt();
}
}

Alternative: JWT Validation in Interceptors​

Alternatively, JWT validation can be handled within each microservice using a custom Interceptor, within services, add an Interceptor to validate JWTs before processing requests.

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader("Authorization");
// Verify the JWT token
// Decode and validate claims
return isValidToken(token);
}
}

Pros and Cons of JWT and mTLS​

ApproachProsCons
mTLSHigh security with mutual authentication.Requires certificate management, adds complexity.
JWTStateless, easily scalable, widely supported.Token expiration handling; replay attacks if not carefully implemented.

<a name="kubernetes-deployment-and-auto-scaling"></a>
## Kubernetes Deployment and Auto-scaling

Scaling services dynamically is fundamental in Kubernetes. Kubernetes provides an effective way to handle **auto-scaling** of microservices based on resource utilization, e.g. CPU, memory, or custom metrics.

Each microservice is balanced using **Spring Cloud LoadBalancer**, ensuring even distribution across replicas.

> **Step 1**: Configuring Horizontal Pod Autoscaler (HPA)

1. Enable auto-scaling in Kubernetes based on CPU usage by defining an HPA resource.

**inventory-hpa.yaml**
```yaml
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
name: inventory-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: inventory-deployment
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 75
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50

Step 2: Implementing Cluster Scaling

Use Kubernetes’ Cluster Autoscaler for scaling nodes as workload demand grows, ensuring optimal resource use without manual intervention.


Ensuring Secure Microservice Communication​

Securing communication between services is critical. Use mTLS (mutual TLS) and JWT tokens for service-to-service authentication within Kubernetes clusters.

Step 1: Configure Mutual TLS (mTLS)​

Istio or Linkerd can help enforce mTLS between services:

apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: your-namespace
spec:
mtls:
mode: STRICT

Summary​

  1. Use ConfigMaps and Secrets for configuration.
  2. Implement autoscaling with HPA.
  3. Secure communication with mTLS and JWT.
  4. Monitor with readiness/liveness probes and Prometheus/Grafana.

This guide provides an architecture blueprint for deploying secure, scalable, and efficient microservices in Kubernetes using Spring Cloud. The API Gateway simplifies external access, service discovery, and JWT-based authentication, while Kubernetes ensures high availability and resilience across services.

Deep Dive into Spring Cloud OpenFeign --- Deprecated

· 阅读需 4 分钟
  1. Introduction
  2. Key Features
  3. Getting Started
  4. Real Production Use Case
  5. Sample Code
  6. Deployment and Usage
  7. Conclusion

Deep Dive into Spring Cloud OpenFeign


Introduction​

Spring Cloud OpenFeign is a declarative HTTP client that simplifies the process of consuming RESTful services in Spring Boot applications. It integrates seamlessly with Spring's dependency injection and configuration mechanisms, making it a powerful tool for microservices architectures. This article provides a deep dive into Spring Cloud OpenFeign, including a real production use case, sample code, and deployment strategies.

Key Features​

  • Declarative REST Client: Define interfaces with annotations to describe the REST API you want to consume.
  • Integration with Spring Boot: Automatically integrates with Spring Boot's dependency injection and configuration mechanisms.
  • Load Balancing: Integrates with Spring Cloud LoadBalancer for client-side load balancing.
  • Error Handling: Provides mechanisms to handle errors and exceptions gracefully.
  • Interceptors: Allows adding custom interceptors to modify requests and responses.

Getting Started​

To use Spring Cloud OpenFeign in your Spring Boot project, add the following dependency to your pom.xml (for Maven) or build.gradle (for Gradle):

Maven:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

Gradle:

implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'

Enable Feign in your Spring Boot application by adding the @EnableFeignClients annotation to your main application class:

import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableFeignClients
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

Real Production Use Case​

Scenario: Microservices Communication in an E-commerce Platform​

In an e-commerce platform, multiple microservices interact to handle various functionalities such as product catalog, user management, and order processing. OpenFeign is used to facilitate communication between these services.

Example: Order Service Communicating with Product Service​

The Order Service needs to retrieve product details from the Product Service to process orders. OpenFeign simplifies this communication by allowing the Order Service to define a Feign client for the Product Service.

Sample Code​

Define the Feign Client​

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "product-service", url = "http://localhost:8081")
public interface ProductServiceClient {

@GetMapping("/products/{productId}")
Product getProduct(@PathVariable("productId") Long productId);
}

Product Class​

public class Product {
private Long id;
private String name;
private Double price;

// Getters and Setters
}

Using the Feign Client in the Order Service​

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

@Autowired
private ProductServiceClient productServiceClient;

public void processOrder(Long productId) {
Product product = productServiceClient.getProduct(productId);
// Process the order using the product details
}
}

Deployment and Usage​

Deployment Strategy​

  1. Containerization: Use Docker to containerize your Spring Boot applications.
  2. Orchestration: Deploy your containers using Kubernetes for orchestration.
  3. Service Discovery: Integrate with a service discovery tool like Eureka or Consul.

Example Deployment with Kubernetes​

Dockerfile​

FROM openjdk:11-jre-slim
COPY target/myapp.jar /myapp.jar
ENTRYPOINT ["java", "-jar", "/myapp.jar"]

Kubernetes Deployment YAML​

apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
spec:
replicas: 3
selector:
matchLabels:
app: order-service
template:
metadata:
labels:
app: order-service
spec:
containers:
- name: order-service
image: myapp:latest
ports:
- containerPort: 8080

Usage in Production​

  1. Monitoring: Use tools like Prometheus and Grafana to monitor your services.
  2. Logging: Implement centralized logging with ELK (Elasticsearch, Logstash, Kibana) stack.
  3. Security: Ensure secure communication using HTTPS and OAuth2 for authentication.

Conclusion​

Spring Cloud OpenFeign is a powerful tool for building declarative HTTP clients in Spring Boot applications. Its integration with the Spring ecosystem, combined with active development and community support, makes it a reliable choice for microservices architectures. By following the steps outlined in this article, you can effectively use OpenFeign in your production environment, facilitating seamless communication between microservices.

Reactive Programming in Spring WebFlux Series - XIII-2

· 阅读需 9 分钟

Deep Dive: Integrating Spring WebFlux with Microservices Architecture


Introduction​

In the previous articles, we have delved into the foundational concepts of Spring WebFlux, Reactor, error handling, data stream transformations, reactive database access, performance optimization, security, testing, deployment and operations, as well as best practices and common pitfalls. This article will focus on integrating Spring WebFlux with microservices architecture to build high-performance, scalable distributed systems.

Microservices Architecture Overview​

Microservices architecture is an approach that breaks down an application into a set of small, independently deployable services, each running in its own process and communicating through lightweight mechanisms, typically HTTP or message queues. The benefits of microservices architecture include:

  • Independent Deployment: Each service can be deployed and updated independently, reducing system downtime.
  • Scalability: Services can be scaled independently, improving resource utilization.
  • Technological Diversity: Different services can use the most suitable technology stacks, increasing flexibility in technology choices.

Integrating Spring WebFlux with Microservices​

Spring WebFlux, as a reactive web framework within the Spring ecosystem, is well-suited for building high-concurrency, low-latency microservices. Here are some key points for integrating Spring WebFlux with microservices.

Using Spring Cloud​

Spring Cloud provides a set of tools to simplify development and management in distributed systems, particularly in microservices architectures based on Spring Boot. Key components include:

  • Spring Cloud Kubernetes: Integrates with Kubernetes for service registration and discovery, configuration, and more.
  • Spring Cloud Gateway: An API gateway built on Spring WebFlux, offering dynamic routing, monitoring, and rate limiting.
  • Spring Cloud Config: Provides centralized configuration management for distributed systems.

Service Registration and Discovery​

Service registration and discovery are crucial components in microservices architecture, allowing services to dynamically register themselves and discover other services. Spring Cloud Kubernetes integrates with Kubernetes' native service discovery mechanisms.

Adding Dependencies​

Add the Spring Cloud Kubernetes dependencies to your service:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-discovery</artifactId>
</dependency>

Configuring Service Registration and Discovery​

Configure service registration and discovery in application.properties:

spring.application.name=book-service
spring.cloud.kubernetes.discovery.enabled=true

Annotating the Main Class​

Annotate your Spring Boot main class with @EnableDiscoveryClient:

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDiscoveryClient
public class BookServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookServiceApplication.class, args);
}
}

API Gateway​

An API gateway is another critical component in microservices architecture, handling all external requests and routing them to the appropriate services. Spring Cloud Gateway is an API gateway built on Spring WebFlux.

Adding Dependencies​

Add the Spring Cloud Gateway dependency to your gateway service:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

Configuring Gateway Routes​

Configure routes in application.properties:

spring.cloud.gateway.routes[0].id=book-service
spring.cloud.gateway.routes[0].uri=lb://book-service
spring.cloud.gateway.routes[0].predicates[0]=Path=/books/**

spring.cloud.gateway.routes[1].id=user-service
spring.cloud.gateway.routes[1].uri=lb://user-service
spring.cloud.gateway.routes[1].predicates[0]=Path=/users/**

spring.cloud.gateway.routes[2].id=order-service
spring.cloud.gateway.routes[2].uri=lb://order-service
spring.cloud.gateway.routes[2].predicates[0]=Path=/orders/**

Client-Side Load Balancing​

Spring Cloud provides client-side load balancing through Spring Cloud LoadBalancer, which allows services to distribute requests across multiple instances.

Adding Dependencies​

Add the Spring Cloud LoadBalancer dependency to your service:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

Configuring Load Balancer​

Configure the load balancer in application.properties:

spring.cloud.loadbalancer.ribbon.enabled=false

Using Load Balancer​

Use the load balancer in your service:

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;

@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}

When you make a request using the WebClient.Builder, you typically specify the service name in the URI (e.g., http://book-service/books). The @LoadBalanced annotation tells Spring Cloud LoadBalancer to intercept this request and resolve the service name (book-service) to the actual service instances.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class BookService {

private final WebClient.Builder webClientBuilder;

@Autowired
public BookService(WebClient.Builder webClientBuilder) {
this.webClientBuilder = webClientBuilder;
}

public Mono<Book> getBookById(Long id) {
return webClientBuilder.build()
.get()
.uri("http://book-service/books/{id}", id)
.retrieve()
.bodyToMono(Book.class);
}
}

Circuit Breaker​

Circuit breakers are an essential pattern in microservices architecture, handling service call failures to prevent fault propagation. Spring Cloud Circuit Breaker provides circuit breaker functionality with support for multiple implementations like Resilience4J.

Adding Dependencies​

Add the Spring Cloud Circuit Breaker and Resilience4J dependencies to your service:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
</dependency>

Configuring Circuit Breaker​

Configure the circuit breaker in application.properties:

resilience4j.circuitbreaker.instances.bookService.failureRateThreshold=50
resilience4j.circuitbreaker.instances.bookService.waitDurationInOpenState=5s
resilience4j.circuitbreaker.instances.bookService.ringBufferSizeInHalfOpenState=10
resilience4j.circuitbreaker.instances.bookService.ringBufferSizeInClosedState=100

Using Circuit Breaker​

Use the circuit breaker in your service:

import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class BookService {

private final ReactiveCircuitBreakerFactory circuitBreakerFactory;
private final BookRepository bookRepository;

public BookService(ReactiveCircuitBreakerFactory circuitBreakerFactory, BookRepository bookRepository) {
this.circuitBreakerFactory = circuitBreakerFactory;
this.bookRepository = bookRepository;
}

public Mono<Book> getBookById(Long id) {
return bookRepository.findById(id)
.transform(it -> circuitBreakerFactory.create("bookService").run(it, throwable -> Mono.just(new Book(id, "Default Book", "Unknown", 0.0))));
}
}

Diagram​

  • Client-Side: WebClient - Alternative of Spring-Cloud OpenFeign
  • API Gateway: Routes
  • BookService: Integerated CircuitBreaker(Actual Implementation is resilience4j)
+-------------------+ +-------------------+ +-------------------+
| Client-Side | | API Gateway | | Actual BookService|
| MultiServiceCaller| | | | |
| | | | | |
| +-------------+ | | +-------------+ | | +-------------+ |
| | WebClient | | | | Routes | | | | Circuit | |
| | | | | | | | | | Breaker | |
| | +---------+ | | | | +---------+ | | | | +---------+ | |
| | | Request | | | | | | Request | | | | | | Request | | |
| | +---------+ | | | | +---------+ | | | | +---------+ | |
| +-------------+ | | +-------------+ | | +-------------+ |
| | | | | |
| | | | | |
| | | | | |
+-------------------+ +-------------------+ +-------------------+

Real-Life Production Use Cases​

Use Case 1: E-commerce Platform​

In an e-commerce platform, multiple microservices interact to handle various functionalities such as product catalog, user management, and order processing. Spring WebFlux and Spring Cloud components can be used to build a scalable and resilient system.

Example: Order Service Communicating with Product Service​

The Order Service needs to retrieve product details from the Product Service to process orders. Spring Cloud Gateway can be used as an API gateway to route requests, and Spring Cloud LoadBalancer can be used for client-side load balancing.

Use Case 2: Financial Services​

In financial services, microservices handle transactions, account management, and reporting. Spring WebFlux can be used to build high-performance services, and Spring Cloud Circuit Breaker can be used to handle failures gracefully.

Example: Transaction Service with Circuit Breaker​

The Transaction Service needs to call the Account Service to validate account balances. If the Account Service is down, the circuit breaker can return a default response to prevent system failure.

Sample Code​

Service Registration and Discovery​

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDiscoveryClient
public class BookServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookServiceApplication.class, args);
}
}

API Gateway​

spring.cloud.gateway.routes[0].id=book-service
spring.cloud.gateway.routes[0].uri=lb://book-service
spring.cloud.gateway.routes[0].predicates[0]=Path=/books/**

spring.cloud.gateway.routes[1].id=user-service
spring.cloud.gateway.routes[1].uri=lb://user-service
spring.cloud.gateway.routes[1].predicates[0]=Path=/users/**

spring.cloud.gateway.routes[2].id=order-service
spring.cloud.gateway.routes[2].uri=lb://order-service
spring.cloud.gateway.routes[2].predicates[0]=Path=/orders/**

Client-Side Load Balancing​

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;

@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}

Using WebClient to Call Different Services​

Create a service class that uses the WebClient.Builder to interact with different registered services:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class MultiServiceCaller {

private final WebClient.Builder webClientBuilder;

@Autowired
public MultiServiceCaller(WebClient.Builder webClientBuilder) {
this.webClientBuilder = webClientBuilder;
}

public Mono<Book> getBookById(Long id) {
return webClientBuilder.build()
.get()
.uri("http://book-service/books/{id}", id)
.retrieve()
.bodyToMono(Book.class);
}

public Mono<User> getUserById(Long id) {
return webClientBuilder.build()
.get()
.uri("http://user-service/users/{id}", id)
.retrieve()
.bodyToMono(User.class);
}

public Mono<Order> getOrderById(Long id) {
return webClientBuilder.build()
.get()
.uri("http://order-service/orders/{id}", id)
.retrieve()
.bodyToMono(Order.class);
}
}

Circuit Breaker​

import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class BookService {

private final ReactiveCircuitBreakerFactory circuitBreakerFactory;
private final BookRepository bookRepository;

public BookService(ReactiveCircuitBreakerFactory circuitBreakerFactory, BookRepository bookRepository) {
this.circuitBreakerFactory = circuitBreakerFactory;
this.bookRepository = bookRepository;
}

public Mono<Book> getBookById(Long id) {
return bookRepository.findById(id)
.transform(it -> circuitBreakerFactory.create("bookService").run(it, throwable -> Mono.just(new Book(id, "Default Book", "Unknown", 0.0))));
}
}

Conclusion​

In this article, we explored how to integrate Spring WebFlux with microservices architecture using the latest Spring Cloud components. By leveraging Spring Cloud Kubernetes, Spring Cloud Gateway, Spring Cloud LoadBalancer, and Spring Cloud Circuit Breaker, we can easily build high-performance, scalable distributed systems. Real-life production use cases and sample code demonstrate the practical application of these components in building resilient and scalable microservices.