Search Tutorials


Spring Cloud Tutorial - Spring Cloud Gateway Filters Example | JavaInUse



Spring Cloud Tutorial - Spring Cloud Gateway Filters Example

In a previous tutorial we had implemented Spring Cloud Gateway Hello World Example. In this tutorial we will be making use of Spring Cloud provided filters and also create custom filters for our spring cloud gateway. In the next tutorial we will be integrating Spring Cloud Gateway with Eureka Service Discovery.
Using Predicates Spring Cloud Gateway determines which route should get called. Once decided the request is the routed to the intended microservice. Before routing this request we can apply some filters to the request. These filters are known as pre filters. After applying the 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. Before returning the response we can again apply some filters to this response. Such filters are called post filters.
spring cloud gateway architecture
As specified in the Spring Cloud Gateway Documentation, Spring Cloud provides a number of built in filters. Also we can create our own custom filter to suit our business requirement. In this tutorial we will be looking at the various Filters that can be used with Spring Cloud Gateway.

Spring Cloud - Table Of Contents

Microservice Registration and Discovery with Spring cloud using Netflix Eureka- Part 1. Microservice Registration and Discovery with Spring cloud using Netflix Eureka - Part 2. Microservice Registration and Discovery with Spring cloud using Netflix Eureka - Part 3. Microservice Registration and Discovery with Spring cloud using Netflix Eureka - Part 4. Spring Cloud- Netflix Eureka + Ribbon Simple Example Spring Cloud- Netflix Eureka + Ribbon + Hystrix Fallback Simple Example Spring Cloud- Netflix Hystrix Circuit Breaker Simple Example Spring Cloud- Netflix Feign REST Client Simple Example Spring Cloud- Netflix Zuul +Eureka Simple Example Spring Cloud Config Server using Native Mode Simple Example Spring Cloud Config Server Using Git Simple Example Spring Boot Admin Simple Example Spring Cloud Stream Tutorial - Publish Message to RabbitMQ Simple Example Spring Cloud Stream Tutorial - Consume Message from RabbitMQ Simple Example Spring Cloud Tutorial - Publish Events Using Spring Cloud Bus Spring Cloud Tutorial - Stream Processing Using Spring Cloud Data Flow Spring Cloud Tutorial - Distributed Log Tracing using Sleuth and Zipkin Example Spring Cloud Tutorial - Spring Cloud Gateway Hello World Example Spring Cloud Tutorial - Spring Cloud Gateway Filters Example Spring Cloud Tutorial - Spring Cloud Gateway + Netflix Eureka Example Spring Cloud Tutorial - Spring Cloud Gateway + Netflix Eureka + Netflix Hystrix Example

Video

This tutorial is explained in the below Youtube Video.

Implementing Spring Cloud Gateway Filters

Spring Cloud Gateway filters can be classified as
  • Spring Cloud Gateway Pre Filters
  • Spring Cloud Gateway Post Filters

spring cloud gateway filter classification
Spring Cloud Filters can be implemented in following two ways-
  • Spring Cloud Gateway Filters using Java Configuration
  • Spring Cloud Gateway Filters using Property Configuration

spring cloud gateway filter implementation

Implementing Spring Cloud Gateway Filters using Java Configuration

We will be modifying the code we had created in the previous tutorial. We will be adding the pre and post filter configuration as follows-
package com.javainuse.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringCloudConfig {

	@Bean
	public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
		return builder.routes()
				.route(r -> r.path("/employee/**")
				//Pre and Post Filters provided by Spring Cloud Gateway
						.filters(f -> f.addRequestHeader("first-request", "first-request-header")
								.addResponseHeader("first-response", "first-response-header"))
						.uri("http://localhost:8081/")
						.id("employeeModule"))

				.route(r -> r.path("/consumer/**")
				//Pre and Post Filters provided by Spring Cloud Gateway
						.filters(f -> f.addRequestHeader("second-request", "second-request-header")
								.addResponseHeader("second-response", "second-response-header"))
						.uri("http://localhost:8082/")
						.id("consumerModule"))
				.build();
	}

}
In the FirstController we extract the request header we have added in the pre filter and print it.
package com.javainuse.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/employee")
public class FirstController {

	@GetMapping("/message")
	public String test(@RequestHeader("first-request") String header) {
		System.out.println(header);
		return "Hello JavaInUse Called in First Service";
	}
}
In the SecondController we extract the request header we have added in the pre filter and print it.
package com.javainuse.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/consumer")
public class SecondController {

	@GetMapping("/message")
	public String test(@RequestHeader("second-request") String header) {
		System.out.println(header);
		return "Hello JavaInUse Called in Second Service";
	}
}
Start the applications-
  • cloud-gateway-service
  • first-service
  • second-service
Run the application.
  • Go to localhost:8080/employee/message- In the console we can see that pre filter has been applied to request.

    spring cloud gateway pre filter console
    In the browser we can see that the post filter has been applied to response.
    spring cloud gateway pre filter
  • Go to localhost:8080/consumer/message-
    In the console we can see that pre filter has been applied to request.
    spring cloud gateway post filter console
    In the browser we can see that the post filter has been applied to response.
    spring cloud gateway post filter

Implementing Spring Cloud Gateway Filters using Property based Configuration

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
Start the applications-
  • cloud-gateway-service
  • first-service
  • second-service
Run the application.
  • Go to localhost:8080/employee/message- In the console we can see that pre filter has been applied to request.

    spring cloud gateway pre filter console
    In the browser we can see that the post filter has been applied to response.
    spring cloud gateway pre filter
  • Go to localhost:8080/consumer/message-
    In the console we can see that pre filter has been applied to request.
    spring cloud gateway post filter console
    In the browser we can see that the post filter has been applied to response.
    spring cloud gateway post filter

Creating Custom Filters

Previously we have used filters that are provided out of the box by Spring Cloud Gateway. But suppose we want to create our own filters to suit our business needs. We can do this by creating custom filters. For this we make use of the AbstractGatewayFilterFactory class.
package com.javainuse.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import reactor.core.publisher.Mono;

@Component
public class CustomFilter extends AbstractGatewayFilterFactory<CustomFilter.Config> {
	public CustomFilter() {
		super(Config.class);
	}

	@Override
	public GatewayFilter apply(Config config) {
		//Custom Pre Filter. Suppose we can extract JWT and perform Authentication
		return (exchange, chain) -> {
			System.out.println("First pre filter" + exchange.getRequest());
			//Custom Post Filter.Suppose we can call error response handler based on error code.
			return chain.filter(exchange).then(Mono.fromRunnable(() -> {
				System.out.println("First post filter");
			}));
		};
	}

	public static class Config {
		// Put the configuration properties
	}
}
Specify the Custom Filter in the route
server:
  port: 8080

spring:
  cloud:
    gateway:
      routes:
      - id: employeeModule
        uri: http://localhost:8081/
        predicates:
        - Path=/employee/**
        filters:
        - CustomFilter
      - id: consumerModule
        uri: http://localhost:8082/
        predicates:
        - Path=/consumer/**
        filters:
        - CustomFilter

Global Filters using Spring Cloud Gateway

Till now we have created filters which we are applying to a specific route. But suppose now we want to apply some filter to all the routes. We can do this by creating Global Filters.
Global Filters can be specified using Java Configuration and Property Based Configuration.

Global Filters using Property Based Configuration

Above we had created a custom filter named CustomFilter by extending the AbstractGatewayFilterFactory. We can specify this filter as a global filter as follows-
server:
  port: 8080

spring:
  cloud:
    gateway:
      default-filters:
      - name: CustomFilter
      routes:
      - id: employeeModule
        uri: http://localhost:8081/
        predicates:
        - Path=/employee/**
      - id: consumerModule
        uri: http://localhost:8082/
        predicates:
        - Path=/consumer/**

Global Filters using Java Based Configuration

We create a bean of type GlobalFilter.
package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;

import reactor.core.publisher.Mono;

@SpringBootApplication
public class APIGatewayApplication {

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

	@Bean
	public GlobalFilter globalFilter() {
		return (exchange, chain) -> {
			System.out.println("First Global filter");
			return chain.filter(exchange).then(Mono.fromRunnable(() -> {
				System.out.println("Second Global filter");
			}));
		};
	}

}

Download Source Code

Download it -
Spring Boot First Microservice
Spring Boot Second Microservice
Spring Cloud Gateway Microservice Using Java Config
Spring Cloud Gateway Microservice Using Properties Config

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions