Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.
Before we begin, it’s recommended to have already completed Spring Config Server, Spring Config Client and Spring Discovery Server.
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
Configure spring.cloud.config.uri
with config server url in bootstrap.yml
.
spring: cloud: config: uri: ${config.url:http://localhost:8001} name: gateway
Add Spring Cloud’s @EnableDiscoveryClient
to register the application to discovery server.
@SpringBootApplication @EnableDiscoveryClient public class SpringGatewayApplication { public static void main(String[] args) { SpringApplication.run(SpringGatewayApplication.class, args); } }
Add discovery server url in the gateway-<profile>.yml
file, available under config folder of config server.
eureka.client.service.url.defaultZone
= http://localhost:8101/eureka,http://localhost:8102/eureka.
Once the properties file of both nodes are updated, restart the config server.
Execute mvn clean install
to build the jar.
In order to test the application, we need to run below command
java -jar -Dspring.profiles.active=dev -Dserver.port=8003 spring-gateway-1.0.0.jar
Note: Start discovery nodes and config server before gateway server.
Once all the applications are running, we can test it by opening below url in browser.
Node 1 – http://localhost:8101/
Node 2 – http://localhost:8102/
You will notice that gateway server has registered itself on both eureka nodes.