How to configure SpringCloud Zuul – Routing and Filtering | SpringBoot

Netflix Zuul is a proxy solution to forward requests to microservices. In the tutorial, JavaSampleApproach will show you way to configure SpringBoot Zuul with routing & filtering.

Related articles:
Client Load Balancing with Spring Cloud Ribbon + Spring Boot
Spring Cloud Centralized Configuration


I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE
– Spring Cloud Zuul: 1.3.0.RELEASE

II. Practice

We create 3 projects: 2 – simple MicroService Applications & 1 – Zuul Proxy Gateway.

1. Create Spring Boot MicroServices

Create 2 MicroService Web Applications.
– Add spring-boot-starter-web for each:

1.1 Create Student service

Student Service runs at: server.port=8081

1.2 Create Lecturer service

Lecturer Service runs at: server.port=8082

2. Create Zuul Proxy Gateway
2.1 Create Spring Boot Zuul Gateway

Create a Spring Boot Zuul Gateway runs at: server.port=8080
– Add needed dependencies: spring-boot-starter-web & spring-cloud-starter-zuul

Configure MicroServices for routing:
students at http://localhost:8081.
lecturers at http://localhost:8082

Enable Zuul Gateway by annotation: @EnableZuulProxy

2.2 Add filters

Zuul has 4 filter types:
pre filters are executed before the request is routed.
route filters uses to route the request.
post filters are executed after the request has been routed.
error filters execute if an error occurs while handling the request.

zuul gateway

For creating a filter, just extends ZuulFilter. Need overview 4 functions:
public String filterType(): specify the type of a filter: (pre, route, post, error) by a String
public int filterOrder(): indicates the order to process this filter.
public boolean shouldFilter(): gives a condition to consider to execute the filter.
public Object run(): functionality of the filter.

In the Zuul Gateway project, we create 4 simple filters, just log info of httprequest/httpresponse while executing:

– 2 Prefilters with difference filterOrder:
PreFilter.java

PreFilter2.java

– 1 route filter:
RouteFilter.java

– 1 post filter:
PostFilter.java

– 1 error filter:
ErrorFilter.java

3. Run & Check results

Build the projects with Spring Boot App mode.
– Make request: http://localhost:8080/students

springboot zuul gateway - students

Zuul Gateway’s Logs:

– Make request: http://localhost:8080/lecturers

springboot zuul gateway - lectures

Zuul Gateway’s Logs:

– Shutdown Lectures Service at 8082
Make the request again: http://localhost:8080/lecturers

springboot zuul gateway - lectures - error filter

Zuul Gateway’s Logs:

III. SourceCode

1. SpringBootLecturer
2. SpringBootStudent
3. SpringBootZuulGateWay


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*