Spring Cloud Zuul and Spring Cloud API Gateway to build a richer gateway

Spring Cloud Zuul and Spring Cloud API Gateway to build a richer gateway

API gateway is the new norm if you are working on microservices or migrating legacy to the new stack. Spring Zuul API gateway is a project from the spring framework family that helps you to implement an application-level gateway.

An API gateway is an API management tool that sits between a client and a collection of backend services. An API gateway acts as a reverse proxy to accept all application programming interface (API) calls, aggregate the various services required to fulfill them and return the appropriate result.

image.png

There are so many paid API gateways like apigee, kong they are very enriched in services but if you are looking for some open source option with your customization with few options then Spring Cloud Zuul is the best option.

In this article, we are building an API gateway using spring cloud zuul.

Zuul handles the dynamic routing of requests to specific microservices. Zuul is built to make it easier to route requests dynamically, monitor various services, and provide a single entry point for all requests, ensuring that all the requests are secure since it handles request filtering before routing to the specific service.

Services:

Let us develop two services:

1. Employee Service: This service will handle employee-related requests and reports.

2. Department Service: This service will handle department-related requests.

In addition to the above services, we will also have the following services:-

Zuul server service:
This service will handle all the requests and routing to other services.

Eureka service: Through this service, other services will discover each other and be able to communicate with each other.

Tech Stack:

  1. Java8

  2. Spring Boot

  3. Spring Cloud

  4. VSCode

  5. Gradle

Project Setup:

Employee Service

  1. Navigate to start.spring.io on your web browser.

  2. Input the project name as “EmployeeService”.

  3. Add Eureka Discovery, Spring Web and Lombok as project dependencies.

  4. Click on the generate button to download the project-generated boilerplate code and dependencies as an archive file.

  5. Unarchive the downloaded and open it in your favorite IDE.

  6. Sync the project to download the dependencies from the central maven repository.

  7. Update the EmployeeServiceApplication class with the code snippet below.

@SpringBootApplication
@EnableDiscoveryClient
public class EmployeeServiceApplication{

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

}

@EnableDiscoveryClient

The @EnableDiscoveryClient annotation is used in Spring Boot applications to enable service discovery and registration with a discovery server, such as Eureka or Consul.

When you annotate a Spring Boot application with @EnableDiscoveryClient, automatically registers with the discovery server and provides metadata about the service, such as the service name, instance ID, IP address, and port number. This allows other services to discover and communicate with the registered service.

@Data
@Builder
@AllArgsConstructor
public class Employee{
    private final String name;
    private final String regNo;
}

Let us create a controller

@RestController
@RequestMapping("/api") 
public class EmployeeController {
    //Returns a list of Employee
    @GetMapping("/employees")
    public ResponseEntity<List<Employee>> test() {
        return new ResponseEntity<>(returnEmployeeList(), HttpStatus.OK);
    }
    //Generates list of Employees
    public List<Employee> returnEmployeeList() {
        List<Employee> employees= new ArrayList<>();
        employees.add(new Employee("Sachin Patil", "112"));
        employees.add(new Employee("Sunil Gavaskar", "212"));
        employees.add(new Employee("Sachin Tendulkar", "312"));
        return employees;
    }
}

properties file:

server.port=8100 
spring.application.name=employee-service #name of the service
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

Insurance Service:

  1. Navigate to start.spring.io on your web browser.

  2. Input the project name as “InsuranceService”.

  3. Add Eureka Discovery, Spring Web and Lombok as project dependencies.

  4. Click on the generate button to download the project-generated boilerplate code and dependencies as an archive file.

  5. Unarchive the downloaded and open it in your favorite IDE.

  6. Sync the project to download the dependencies from the central maven repository.

  7. Update the InsuranceServiceApplication class with the code snippet below.

Let us define the model

@Data
@AllArgsConstructor
public class Insurance{
    private final String name;
    private final String id;
}

Define the controller which will help us to do operations on insurance domain

@RestController
@RequestMapping("/api/insurance")
public class InsuranceController {
    //Function returns a list of insurances
    @GetMapping
    public ResponseEntity<List<Insurance>> getInsurances() {
        return new ResponseEntity<>(getInsuranceList(), HttpStatus.OK);
    }
    //Function generates a list of Insurances
    private List<Insurance> getInsuranceList() {
        List<Insurance> insurances = new ArrayList<>();
        insurances.add(new Insurance("Medical", "1"));
        insurances.add(new Insurance("Health Insurance", "2"));
        insurances.add(new Insurance("Term Insurance", "3"));
        return courses;
    }
}

Application java file

@SpringBootApplication
@EnableDiscoveryClient
public class InsuranceServiceApplication {

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

}

properties file

server.port=8200 
spring.application.name=course-service # The name of the service
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

Zuul Service

  1. Navigate to start.spring.io on your web browser.

  2. Input the project name as “ZuulService”.

  3. Add Eureka Server as the project dependency.

  4. Unarchive the downloaded and open it in your favorite IDE.

  5. Add the dependency below to the dependencies section on the build.gradle file.

starter-netflix-zuul
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-zuul:2.2.10.RELEASE'

Application java class

@SpringBootApplication
@EnableZuulProxy
public class ZuulServerApplication {

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

}

properties file

server.port=8050 # The port for the service
spring.application.name=zuul-edge-server # The name of the service
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

Eureka Service

Now let us develop a eureka service

  1. Navigate to start.spring.io on your web browser.

  2. Input the project name as “EurekaService”.

  3. Add project dependency.

  4. Unarchive the downloaded and open it in your favorite IDE.

  5. Add the dependency below to the dependencies section on the build.gradle file.

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

}

application properties file

server.port=8761 # The port for the service
eureka.client.registerWithEureka=false eureka.client.fetchRegistry=false 
eureka.server.waitTimeInMsWhenSyncEmpty=0

Run the services and make an API call through the Zuul gateway to course service through http://localhost:8050/api/insurance/. We get the response shown below. We can make API requests to the course and student services through the Zuul service. Run all the spring boot applications and enjoy the coding.

Conclusion

In this article, both Spring Cloud Zuul and Spring Cloud API Gateway are powerful tools for building a gateway that can handle multiple services and provide a centralized entry point for clients. Spring Cloud Zuul is a proven and reliable tool that has been around for many years and provides a range of features for routing, filtering, and load balancing. It is also compatible with various service discovery tools such as Eureka, Consul, and ZooKeeper.

On the other hand, Spring Cloud API Gateway is a newer and more flexible tool that provides greater control over the gateway functionality. It allows developers to write custom filters and provides better integration with reactive programming.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!