by BehindJava

How to create a Spring Cloud API Gateway project in the Spring Boot

Home » microservices » How to create a Spring Cloud API Gateway project in the Spring Boot

In this tutorial we are going to learn about creating a Spring Cloud API Gateway project in the Spring Boot.

Firstly, generate a Spring Boot project using Spring Initializr as show in the below image and add the required dependencies i.e., Gateway to make our application act as a Spring Cloud API Gateway, Eureka client since we are registering our API Gateway in Eureka server and web, Dev Tools for automatic restart of the server upon saving changes.

gateway

Once the project is generated. It is download as a ZIP file, UNZIP the project and import in your Spring Tool Suite and go through the dependencies downloaded you’ll notice the web flux dependency which is automatically downloaded which enables reactive programming.

Since we need to register our API Gateway in our Eureka server as a Eureka client, we need add an annotation called @EnableEurekaClient in the main class as shown below.

Code Snippet:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClientpublic class ApiGatewayApplication {

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

}

Now we need to add few configurations under src/main/resources in the application.properties as shown below.

Code Snippet:

server.port=8082
spring.application.name=api-gateway
eureka.client.service-url.defaultZone=http://localhost:8010/eureka
spring.cloud.gateway.discovery.locator.enabled=true

Here we’ll provide the server.port=8082 followed by application name and Eureka client service URL as http://localhost:8010/eureka since Eureka server is running on 8010 port number.

Once our basic API Gateway configuration is ready. Start the Eureka server followed by APIGateway and UserMicroservice applications as Spring Boot App and hit the URL on which our Eureka server is running i.e. http://localhost:8010/ and you can see the UserMicroservice and APIGateway as the Instances currently registered with Eureka as shown below.

eureka

Now to hit the HTTP handler mapping Get that is specified in the UserMicroservie. we need to specify the URL with the application name registered with the Eureka Server i.e. user-ms1 as follows http://localhost:8082/USER-MS1/users/status/check . Since the HTTP request is routed through the APIGateway and you can see the response as shown in the below image.

postmanapi