Implementing Spring Cloud Gateway Filters

Reading Time: 3 minutes

Spring Cloud provides a different type of built in filters .So, they are many different type of Spring cloud Gateway filters. Also, we can create our own custom filters to suit our requirement.

Spring Cloud Gateway Filters can be divided in two categories:

  • Pre Filters
  • Post Filters

Using Predicates Spring Cloud Gateway determines which route should get called. Once it is decided the request is the routed to the intended microservice.

After applying the Pre filters the intended micoservice call is made and the response is returned back to the Spring Cloud Gateway which returns this response back to the caller.Here we apply Post filters.

Pre Filters: The filters which we apply to the request before routing are known as Pre filters.

Post Filters:The filters which apply to the response before returning the response are known as Post filters.

Also,There are two ways to implement Spring Cloud Filters:

  • Using Java Based Configuration
  • Using Property Based Configuration

In this blog we will only look at one of the two.So,lets see how it works.

Implementing Spring Cloud Filters Using Property based Configuration

We have three services:

  • cloud-gateway-service
  • first-service
  • second-service

First, In application.yml, add filters,

server:
  port: 8080

spring:
  cloud:
    gateway:
      routes:
      - id: employeeModule
        uri: http://localhost:8081/
        predicates:
        - Path=/employee/**
        filters:
        - AddRequestHeader=first-request, first-request-header
        - AddResponseHeader=first-response, first-response-header
      - id: consumerModule
        uri: http://localhost:8082/
        predicates:
        - Path=/consumer/**
        filters:
        - AddRequestHeader=second-request, second-request-header
        - AddResponseHeader=second-response, second-response-header

Now,Start the Application with services.

Next,Run the application

Go to localhost:8080/employee/message:

Here,in the console we can see that Pre filter has been applied to the request before routing it:

Also,In the browser we can see that Post filter has been applied to the response before returning it:

Go to localhost:8080/consumer/message:

Here,in the console we can see that Pre filter has been applied to the request before routing it:

Also,In the browser we can see that Post filter has been applied to the response before returning it:

Conclusion:

We got glimpse of spring cloud gateway filter types and how to implement them.Thank You for reading. For more, you can refer to: https://cloud.spring.io/spring-cloud-gateway/reference/html/

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading