Getting Started With Spring Cloud Gateway
In this article, we will integrate spring cloud gateway with a microservice-based architecture application using spring cloud.
Join the DZone community and get the full member experience.
Join For FreeIn this article, we will integrate spring cloud gateway with a microservice-based architecture application using spring cloud. In the process, we will use spring cloud gateway as a gateway provider, Netflix Eureka as a discovery server, with circuit breaker pattern using Netflix Hystrix.
Let's quickly get started with the implementation of it.
Discovery Server Implementation
In a microservice architecture, service discovery is one of the key tenets. Service discovery automates the process of multiple instance creations on demand and provides high availability of our microservices.
Below are the pom.xml and application.yml configuration for integrating Netflix Eureka Discovery with Spring Cloud.
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
application.yml
spring:
application:
name: discovery-service
eureka:
client:
eureka-server-connect-timeout-seconds: 5
enabled: true
fetch-registry: false
register-with-eureka: false
server:
port: 8761
Project Setup
First, we will generate a sample spring boot project from https://start.spring.io and import into the workspace. The selected dependencies are Gateway, Hystrix, and Actuator.
We will also add spring-cloud-starter-netflix-eureka-client dependency in our pom.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Spring Cloud Route Configuration
The route is the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if an aggregate predicate is true.
Spring Cloud Gateway provides many built-in Route Predicate Factories such as Path, Host, Date/Time, Method, Header, etc. We can use these built-in routes with conjunction with and() or () to define our routes. Once a request reaches to the gateway, the first thing gateway does is to match the request with each of the available route based on the predicate defined and the request is routed to the matched route.
Below is our route configuration. We have 2 different routes defined for our 2 microservices — first-service and second-service.
BeanConfig.java
package com.devglan.gatewayservice;
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 BeanConfig {
@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/api/v1/first/**")
.filters(f -> f.rewritePath("/api/v1/first/(?.*)", "/${remains}")
.addRequestHeader("X-first-Header", "first-service-header")
.hystrix(c -> c.setName("hystrix")
.setFallbackUri("forward:/fallback/first")))
.uri("lb://FIRST-SERVICE/")
.id("first-service"))
.route(r -> r.path("/api/v1/second/**")
.filters(f -> f.rewritePath("/api/v1/second/(?.*)", "/${remains}")
.hystrix(c -> c.setName("hystrix")
.setFallbackUri("forward:/fallback/second")))
.uri("lb://SECOND-SERVICE/")
.id("second-service"))
.build();
}
}
Spring Cloud Gateway Application Config
hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 2000
spring:
application:
name: api-gateway
server:
port: 8088
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka
register-with-eureka: false
instance:
preferIpAddress: true
management:
endpoints:
web:
exposure:
include: hystrix.stream
Microservices Implementation
First Service
These services are a very simple implementation with only one controller defined for demo purpose.
FirstController.java
package com.devglan.gatewayservice.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class FirstController {
@GetMapping("/test")
public String test(@RequestHeader("X-first-Header") String headerValue){
return headerValue;
}
}
application.yaml
spring:
application:
name: first-service
server:
port: 8086
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
Second Service Implementation
@RestController
public class SecondController {
@GetMapping("/second")
public String test(@RequestHeader("X-second-Header") String headerValue){
return headerValue;
}
}
application.yaml
spring:
application:
name: second-service
server:
port: 8087
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
Now, as per the route configuration, the request matching the regex /api/v1/first/** will be forwarded to first-service whereas the request matching the regex /api/v1/second/** will be forwarded to second-service.
Conclusion
This concludes an example of using Spring Cloud Gateway to route requests to multiple services running downstream. Next, we can extend this example to integrate security at the gateway level.
Published at DZone with permission of Dhiraj Ray. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments