SoFunction
Updated on 2025-04-07

SpringCloud Zuul and Gateway instance code (building method)

1. What are Spring Cloud Zuul and Spring Cloud Gateway

Spring Cloud Zuul and Spring Cloud Gateway are both components provided by the Spring Cloud framework for building API gateways in microservice architectures.

  • Spring Cloud Zuul: Spring Cloud Zuul is a microservice gateway component built on Netflix Zuul. It provides routing, load balancing, fault tolerance, security and other functions. Zuul uses a synchronous blocking model for smaller-scale microservice architectures. However, it should be noted that Spring Cloud Zuul has now entered maintenance mode, and Spring Cloud officially recommends using Spring Cloud Gateway as an alternative.
  • Spring Cloud Gateway: Spring Cloud Gateway is the officially recommended API gateway solution for Spring Cloud. It is built on Spring Framework 5 and Project Reactor and uses an asynchronous non-blocking model for higher performance and throughput. Spring Cloud Gateway provides functional features such as dynamic routing, filter chain, integrated service discovery, circuit breaker, etc. It also supports Java and functional programming APIs, with more advanced customization and expansion capabilities.

Both components can be used to build API gateways in microservice architectures, and their choice depends on specific requirements and scenarios.

Spring Cloud Gateway is recommended if you need higher performance, more flexible customization capabilities, and better integration with the Spring ecosystem.

If you are already using Netflix's ecosystem components and are not particularly high in performance requirements, consider using Spring Cloud Zuul.

2. Simple examples of Spring Cloud Zuul

  • Create a Spring Boot project and add dependencies:Create a new Spring Boot application in your project and add the following dependencies. If you are using Maven, you can add the following dependencies to the file:
<dependencies>
    <dependency>
        <groupId></groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
</dependencies>
  • Enable Zuul Gateway:Add the @EnableZuulProxy annotation on the main class of your Spring Boot application to enable the Zuul gateway. For example:
import ;
import ;
import ;

@SpringBootApplication
@EnableZuulProxy
public class YourApplication {

    public static void main(String[] args) {
        (, args);
    }
}
  • Configure Zuul routing rules:Configure Zuul's routing rules in or in the file. For example, the following is an example configuration for forwarding requests under the /api/** path to /api/**:
zuul:
  routes:
    example-service:
      path: /api/**
      url: /api

In the example above, example-service is a custom route name, path specifies the matching path pattern, and url specifies the target URL to be forwarded to.

  • Run the application and access the Zuul gateway:Launch your application and forward the request using Zuul gateway. For example, if your application is running at http://localhost:8080, you can send a request to http://localhost:8080/api/example, which will be forwarded to /api/example by Zuul Gateway.

This is a simple example of using Zuul Gateway.

By configuring different routing rules, you can implement request forwarding, load balancing, routing filtering and other functions.

You can also add custom filters to process requests and responses.

Please note that Zuul has been declared deprecated by Spring Cloud, and it is recommended to use Spring Cloud Gateway as an alternative.

3. Simple examples of Spring Cloud Gateway (recommended use)

  • Create a Spring Boot project and add dependencies:Create a new Spring Boot application in your project and add the following dependencies. If you are using Maven, you can add the following dependencies to the file:
<dependencies>
    <dependency>
        <groupId></groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
</dependencies>
  • Configure Spring Cloud Gateway routing rules:Configure Spring Cloud Gateway routing rules in or in the file. For example, the following is an example configuration for forwarding requests under the /api/** path to /api/**:
spring:
  cloud:
    gateway:
      routes:
        - id: example-service
          uri: /api
          predicates:
            - Path=/api/**

In the example above, example-service is a custom route ID, uri specifies the target URL to be forwarded to, and predicates specifies the matching path pattern.

  • Run the application and access the Spring Cloud Gateway:Launch your application and forward requests using Spring Cloud Gateway. For example, if your application is running at http://localhost:8080, you can send a request to http://localhost:8080/api/example, which will be forwarded to /api/example by Spring Cloud Gateway.
  • Add a custom filter (optional):You can add custom filters to process requests and responses. For example, you could create a custom filter class that implements the GlobalFilter interface and register it in the application. Filters can be used for authentication, logging, request conversion and other operations. Run the application and access the Zuul Gateway: Launch your application and forward the request using the Zuul Gateway. For example, if your application is running at http://localhost:8080, you can send a request to http://localhost:8080/api/example, which will be forwarded to /api/example by Zuul Gateway.
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Component
public class CustomFilter implements GlobalFilter, Ordered {

    @Override
    public Mono&lt;Void&gt; filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // Write your filter logic here        // You can obtain request and response information through the exchange object and perform related processing
        // Example: Check whether the request header contains specific authentication information        String authHeader = ().getHeaders().getFirst("Authorization");
        if (authHeader == null || ()) {
            ().setStatusCode();
            return ().setComplete();
        }

        // Continue to perform subsequent filter and routing processing        return (exchange);
    }

    @Override
    public int getOrder() {
        // Set the execution order of the filter        return Ordered.HIGHEST_PRECEDENCE;
    }
}

In the above example, CustomFilter is a custom filter class that implements the GlobalFilter interface and the Ordered interface. You can write your own filter logic in the filter method and set the order of execution of the filter in the getOrder method.

This is a simple example of using Spring Cloud Gateway. By configuring routing rules and adding custom filters, you can implement request forwarding, load balancing, routing filtering and other functions. Spring Cloud Gateway also provides many other features, such as circuit breakers, current limiting, retry, etc., which you can configure and use according to your specific needs.

4. Simple examples of Spring Cloud Gateway load balancing

In Spring Cloud Gateway, you can use LoadBalancerClient or DiscoveryClient to achieve load balancing. Here is an example of load balancing using LoadBalancerClient:

  • Add dependencies:Add the following dependencies to your Spring Boot project. If you are using Maven, you can add the following dependencies to the file:
<dependencies>
    <dependency>
        <groupId></groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    </dependency>
</dependencies>
  • Configure routing rules:Configure Spring Cloud Gateway routing rules in or in the file to specify the target service for load balancing. For example:
spring:
 cloud:
   gateway:
     routes:
       - id: example-service
         uri: lb://example-service
         predicates:
           - Path=/api/**

In the above example, example-service is the name of a service, and lb://example-service means calling the example-service service through load balancing.

  • Create a custom LoadBalancerClient configuration class:Create a custom LoadBalancerClient configuration class to configure load balancing policies. For example:
import ;
import ;
import ;
import ;
import ;
import ;

@Configuration
public class LoadBalancerConfig {

    @Bean
    public LoadBalancerClientFilter loadBalancerClientFilter(LoadBalancerClient loadBalancerClient,
                                                             GatewayLoadBalancerProperties loadBalancerProperties) {
        return new LoadBalancerClientFilter(loadBalancerClient, loadBalancerProperties);
    }

    @Bean
    public LoadBalancerClient loadBalancerClient() {
        return new MyLoadBalancerClient();
    }

    private static class MyLoadBalancerClient implements LoadBalancerClient {

        @Override
        public &lt;T&gt; T execute(String serviceId, LoadBalancerRequest&lt;T&gt; request) {
            // Implement your load balancing logic here            // You can use the load balancing algorithm to select an instance of the target service            // The sample code here directly returns a fixed target service instance            ServiceInstance serviceInstance = new DefaultServiceInstance(serviceId, "example-host", 8080, false);
            return (serviceInstance);
        }

        @Override
        public &lt;T&gt; T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest&lt;T&gt; request) {
            return (serviceInstance);
        }

        @Override
        public URI reconstructURI(ServiceInstance instance, URI original) {
            return ();
        }

        @Override
        public ServiceInstance choose(String serviceId) {
            // Implement your load balancing logic here            // You can use the load balancing algorithm to select an instance of the target service            // The sample code here directly returns a fixed target service instance            return new DefaultServiceInstance(serviceId, "example-host", 8080, false);
        }
    }
}

In the example above, MyLoadBalancerClient is a custom LoadBalancerClient implementation where you can implement your own load balancing logic. The sample code directly returns a fixed target service instance, and you can choose the appropriate load balancing algorithm according to actual needs.

  • Run the application and access the Spring Cloud Gateway:Launch your application and forward requests using Spring Cloud Gateway. Depending on the load balancing configuration, the request will be forwarded to different instances of the target service.

This is an example of load balancing using LoadBalancerClient.

You can select the appropriate load balancing algorithm in the customized LoadBalancerClient implementation according to actual needs, and make dynamic adjustments based on information such as the health status of the service instance.

In addition, you can also use DiscoveryClient to achieve service discovery-based load balancing, which can be integrated with service registries (such as Eureka, Consul) to automatically obtain available service instances.

5. Summary

This article briefly describes simple examples of Spring Cloud Zuul and Spring Cloud Gateway, and there are many features that need to be practiced by everyone themselves.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.