Spring Cloud - Creating Gateway Application



The Gateway Server is bundled with Spring Cloud dependency. You can download the Spring Boot project from Spring Initializer page https://start.spring.io/ and choose the Zuul Server dependency.

Creating Gateway Server Application

You will have to add the Spring Cloud Starter Gateway and dependency in our build configuration file.

Maven users will have to add the following dependency in your pom.xml file −

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

Example - Gateway Application

Once you open the downloaded spring boot project as mentioned above, we need to update source code as below −

We are annotating with @EnableDiscoveryClient because we want to use Eureka service discovery.

GatewayApplication.java

package com.tutorialspoint.gateway;

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

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {

   public static void main(String[] args) {
      SpringApplication.run(GatewayApplication.class, args);
   }	
	
   @Bean
   public RouteLocator myRoutes(RouteLocatorBuilder builder) {
      return builder.routes()
         .route(p -> p
            .path("/customer/**")           
            .uri("http://localhost:8080/customer-service"))
         .route(p -> p
            .path("/restaurant/**")           
            .uri("http://localhost:8080/restaurant-service"))
            .build();
   }
}

application.properties

Let us write a simple configuration for the Gateway for our Restaurant and Customer service.

spring.application.name=restaurant-gateway-service

server.port=8084
eureka.client.service-url.defaultZone=http://localhost:8761/eureka

Points to note about the above configuration −

  • We have enabled the discovery.locator to ensure that the gateway can read from the Eureka server.

  • We have used Path predicated here to route the request. What this means is that any request which begins with /customer would be routed to Customer Service and for /restaurant, we will forward that request to Restaurant Service.

Now our Gateway application is ready for testing which will perform in next chapter.

Advertisements