Spring Boot Microservices — Part4 — APIGW

Prateek
2 min readMay 7, 2022

--

In this tutorial I will implement the APIGW using Spring Cloud API Gateway.

pom.xml

<?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>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>api-gateway-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-gateway-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2021.0.2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</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>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.properties

spring.application.name=api-gateway
spring.cloud.gateway.discovery.locator.enabled
=true
spring.cloud.gateway.discovery.locator.lower-case-service-id
=true

eureka.instance.instance-id
=${spring.application.name}-${random.uuid}
spring.cloud.loadbalancer.ribbon.enabled
=false

spring.cloud.gateway.routes[0].id
=product-service
spring.cloud.gateway.routes[0].uri
=lb://product-service
spring.cloud.gateway.routes[0].predicates[0]
=Path=/api/product

MainApp.java

package com.example;

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

@SpringBootApplication
@EnableEurekaClient
public class ApiGatewayServiceApplication {

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

}

Start the api-gateway-service

POST — http://localhost:8080/api/product

GET — http://localhost:8080/api/product

It shows APIGW works fine!

--

--

Prateek
Prateek

Written by Prateek

Java Developer and enthusiast

No responses yet