DEV Community

eidher
eidher

Posted on • Edited on

3

Spring Cloud Gateway

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.
https://spring.io/projects/spring-cloud-gateway

First, configure the project as a Eureka client as was explained here. Then, add this dependency:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

If you add the next properties you can access other services registered in Eureka:

spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true
Enter fullscreen mode Exit fullscreen mode

The second property is optional and allows us to use lowercase to access the service. For instance, if you have a eureka client service named ACCOUNTS-MICROSERVICE, and the API Gateway project is running on port 8765 you can use this url: http://localhost:8765/accounts-microservice/accounts-microservice/accountDetails/1. Now, you are accessing the accounts-microservice service through the API gateway.

You can create a custom router for adding headers, parameters, and routing:

@Bean
public RouteLocator gatewayRouter(RouteLocatorBuilder builder) {
  return builder.routes()
      .route(p -> p.path("/accounts-microservice/**")
          .filters(f -> f
              .addRequestHeader("MyHeader", "MyURI")
              .addRequestParameter("Param", "MyValue"))
          .uri("lb://accounts-microservice"))
      .build();
}
Enter fullscreen mode Exit fullscreen mode

Now, you can remove the two previous properties and use this simpler URL: http://localhost:8765/accounts-microservice/accountDetails/1. You can see the new header and parameter in the request. Besides, you can chain as many routes as you want in the same builder, add path rewrites, etc.

Additionally, Spring Cloud Gateway provides a GlobalFilter to handle cross-cutting concerns such as logging, lets see an example:

@Component
public class LoggingFilter implements GlobalFilter {

  private final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);

  @Override
  public Mono<Void> filter(ServerWebExchange exchange,
      GatewayFilterChain chain) {
    logger.info("Path of the request received -> {}",
        exchange.getRequest().getPath());
    return chain.filter(exchange);
  }

}
Enter fullscreen mode Exit fullscreen mode

For more information see: https://www.baeldung.com/spring-cloud-gateway

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay