Why use gateway

2. Gateway Entry Case

1. Create projects

1.1 Adding Coordinates
<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13. RELEASE</version>
        <relativePath /> <! -- lookup parent from repository -->
    </parent>
    <groupId>com.luyi</groupId>
    <artifactId>zuul-gateway</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>zuul-gateway</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code
1. Modify the configuration file
Spring.application. Name =zuul-gateway server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
1.3 Modifying the Startup Class
// Enable the gateway proxy
@EnableZuulProxy
@SpringBootApplication
public class ZuulApplication {
    public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); }}Copy the code
1.4 Requesting Services through the Gateway

Access: http://IP: Gateway port number/requested service name/url accessed

3. Four methods of routing rules for routers

1. Create projects

2. Use the URL to specify the routing mode

2.1 Modifying the Configuration File
Spring.application. Name =zuul-gateway-route server.port=9030 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ #1. Route specify :URL specify keyword, Zuul.routes. Ego-product-provider. Path =/ego-product-provider/** Zuul. Routes. Ego - product - provider. Url = http://127.0.0.1:9001/Copy the code
2.2 Wildcard Meanings

? : Matches any single character

* : Matches any number of any characters, but cannot add a slash

** : Matches any number of any characters

3. Use the service to specify the routing mode

1 # route /suibian/ to eureka ego-product-provider # zuul.routes Path # rule: Path =/suibian/** serviceId= Eureka service name #zuul.routes.ego-product-provider #zuul.routes.ego-product-provider.service-id=ego-product-provider #3. 2 #zuul.routes = 2 #zuul.routes = 2 #zuul.routes = 2 #zuul.routes = 2 #zuul.routes zuul.routes.ego-product-provider.path=/suibian/**Copy the code

4. Route exclusion

#4. Route exclusion: This address will be empty if certain services are excluded. http://127.0.0.1:9030/ego-product-provider/product/findAll # # multiple services using comma-separated zuul. Ignored - services = ego - the product - the provider # 5. # Because there are too many routes, it is impossible to add all services manually, so the route excludes all services. Ignored -services=* #zuul.routes. Ego-product-provider =/ego-product-provider/** #6 #zuul.ignored- Patterns =/**/findAll/** zuul.routes.ego-product-provider.path=/ego-product-provider/**Copy the code

5. Add a route prefix

# 7. Add prefix: routing path for all add prefix # # must be changed to http://127.0.0.1:9030/ego-product-provider/product/findAll # http://127.0.0.1:9030/api/suibian/product/findAll # zuul. Prefix = / API zuul routes. The ego - the product - the provider. The path = / suibian * *Copy the code

4. Customize gateway filters

1. Write a gateway filter

1.1 Creating a Project
1.2 Adding Coordinates
<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13. RELEASE</version>
        <relativePath /> <! -- lookup parent from repository -->
    </parent>
    <groupId>com.luyi</groupId>
    <artifactId>zuul-gateway-filter</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>zuul-gateway-filter</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code
1.3 Modifying the Configuration File
Spring.application. Name =zuul-gateway-filter server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
1.4 write filter
@Component
public class LogFilter extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogFilter.class);

    /** * Filter type, which determines when the filter is executed *@return* /
    @Override
    public String filterType(a) {
        // Execute before routing
        return "pre";
    }

    /** * Filter execution order: indicates the order by the returned integer, the smaller the value, the higher the priority *@return* /
    @Override
    public int filterOrder(a) {
        return 0;
    }

    /** * Whether to enable the filter. The default value is false *@return* /
    @Override
    public boolean shouldFilter(a) {
        return true;
    }

    /** * Filter content: write the filter logic in the run method *@return* /
    @Override
    public Object run(a) {
        // Get the request context
        RequestContext requestContext = RequestContext.getCurrentContext();
        // Get the request mode
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("LogFilter... method={},url={}", request.getMethod(), request.getRequestURL().toString());
        return null; }}Copy the code
1.5 Modifying the Startup Class
// Enable the gateway proxy
@EnableZuulProxy
@SpringBootApplication
public class ZuulApplication {
    public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); }}Copy the code

2. Filter type

3.Zuul request lifecycle

4. Use the gateway filter to implement permission verification

Requirement: Check whether a user logs in using the Token in the gateway filter
4.1 Creating a Project
4.2 Adding Coordinates
<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13. RELEASE</version>
        <relativePath /> <! -- lookup parent from repository -->
    </parent>
    <groupId>com.luyi</groupId>
    <artifactId>zuul-gateway-example</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>zuul-gateway-example</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Copy the code
4.3 Modifying the Configuration File
Spring.application. Name =zuul-gateway-example server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
4.4 create AccessFilter
/** * Verify login permission */
@Component
public class AccessFilter extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccessFilter.class);

    /** * Filter type, which determines when the filter is executed *@return* /
    @Override
    public String filterType(a) {
        // Execute before routing
        return "pre";
    }

    /** * Filter execution order: indicates the order by the returned integer, the smaller the value, the higher the priority *@return* /
    @Override
    public int filterOrder(a) {
        return 0;
    }

    /** * Whether to enable the filter. The default value is false *@return* /
    @Override
    public boolean shouldFilter(a) {
        return true;
    }

    /** * Filter content: write the filter logic in the run method *@return* /
    @Override
    public Object run(a) {
        // Get the request context
        RequestContext requestContext = RequestContext.getCurrentContext();
        // Get the request mode
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------pre1------------------------");
        // Get the token in the form
        String token = request.getParameter("token");
        // Check the token
        if (token == null){
            LOGGER.warn("token is null.");
            requestContext.setSendZuulResponse(false);  // Indicates the end of the request
            // Indicates that there is no token
            requestContext.setResponseStatusCode(401);
            // Response content
            requestContext.setResponseBody("{'result':'token is null.'}");
            // Response type
            requestContext.getResponse().setContentType("text/html; charset=utf-8");
        }else{
            // Access the Redis service for verification
            LOGGER.info("token is ok.");
        }
        return null; }}Copy the code

5. Demonstrate the execution sequence and POST type of the gateway filter

5.1 Demonstration of the execution sequence of gateway Filters

AccessFilter

/** ** execute order demo */
@Component
public class AccessFilter extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccessFilter.class);

    /** * Filter type, which determines when the filter is executed *@return* /
    @Override
    public String filterType(a) {
        // Execute before routing
        return "pre";
    }

    /** * Filter execution order: indicates the order by the returned integer, the smaller the value, the higher the priority *@return* /
    @Override
    public int filterOrder(a) {
        return 0;
    }

    /** * Whether to enable the filter. The default value is false *@return* /
    @Override
    public boolean shouldFilter(a) {
        return true;
    }

    /** * Filter content: write the filter logic in the run method *@return* /
    @Override
    public Object run(a) {
        // Get the request context
        RequestContext requestContext = RequestContext.getCurrentContext();
        // Get the request mode
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------pre1------------------------");
        // Get the token in the form
        String token = request.getParameter("token");
        // Check the token
        if (token == null){
            LOGGER.warn("token is null.");
            requestContext.setSendZuulResponse(false);  // Indicates the end of the request
            // Indicates that there is no token
            requestContext.setResponseStatusCode(401);
            // Response content
            requestContext.setResponseBody("{'result':'token is null.'}");
            // Response type
            requestContext.getResponse().setContentType("text/html; charset=utf-8");
        }else{
            // Access the Redis service for verification
            LOGGER.info("token is ok.");
        }
        return null; }}Copy the code

AccessFilter2

/** ** execute order demo */
@Component
public class AccessFilter2 extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccessFilter2.class);

    /** * Filter type, which determines when the filter is executed *@return* /
    @Override
    public String filterType(a) {
        // Execute before routing
        return "pre";
    }

    /** * Filter execution order: indicates the order by the returned integer, the smaller the value, the higher the priority *@return* /
    @Override
    public int filterOrder(a) {
        return 1;
    }

    /** * Whether to enable the filter. The default value is false *@return* /
    @Override
    public boolean shouldFilter(a) {
        return true;
    }

    /** * Filter content: write the filter logic in the run method *@return* /
    @Override
    public Object run(a) {
        // Get the request context
        RequestContext requestContext = RequestContext.getCurrentContext();
        // Get the request mode
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------pre2------------------------");

        return null; }}Copy the code

5.2 Post Type Demo
/** * Post type demo */
@Component
public class PostFilter extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(PostFilter.class);

    /** * Filter type, which determines when the filter is executed *@return* /
    @Override
    public String filterType(a) {
        return "post";
    }
    
    /** * Filter execution order: indicates the order by the returned integer, the smaller the value, the higher the priority *@return* /
    @Override
    public int filterOrder(a) {
        return 0;
    }

    /** * Whether to enable the filter. The default value is false *@return* /
    @Override
    public boolean shouldFilter(a) {
        return true;
    }

    /** * Filter content: write the filter logic in the run method *@return* /
    @Override
    public Object run(a) {
        // Get the request context
        RequestContext requestContext = RequestContext.getCurrentContext();
        // Get the request mode
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------post------------------------");
        return null; }}Copy the code

6. Use the gateway filter to uniformly handle exceptions

6.1 create ErrorFilter
/** * error type demo */
@Component
public class ErrorFilter extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ErrorFilter.class);

    /** * Filter type, which determines when the filter is executed *@return* /
    @Override
    public String filterType(a) {
        return "error";
    }

    /** * Filter execution order: indicates the order by the returned integer, the smaller the value, the higher the priority *@return* /
    @Override
    public int filterOrder(a) {
        return 1;
    }

    /** * Whether to enable the filter. The default value is false *@return* /
    @Override
    public boolean shouldFilter(a) {
        return true;
    }

    /** * Filter content: write the filter logic in the run method *@return* /
    @Override
    public Object run(a) {
        // Get the request context
        RequestContext requestContext = RequestContext.getCurrentContext();
        // Get the request mode
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------error------------------------");

        return null; }}Copy the code
6.2 create ExceptionHandler
/** * Handle abnormal response contents */
@RestController
public class ExceptionHandler implements ErrorController {
    @Override
    public String getErrorPath(a) {
        return "/error";
    }

    @RequestMapping(value = "error")
    public String error(a){
        return "{'result':'500 error'}"; }}Copy the code

5. Gateway fault tolerance

1. Zuul and Hystrix are seamlessly integrated

The Jar package for Zuul contains the Jar package for Hystrix. So we don’t need to add hystrix coordinates to the project.

2. Access the data monitoring flow of the gateway service

3. Start the dashboard-view service to monitor health status

4. Perform service degradation on the gateway

4.1 Creating a Project
4.2 Adding Coordinates
<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13. RELEASE</version>
        <relativePath /> <! -- lookup parent from repository -->
    </parent>
    <groupId>com.luyi</groupId>
    <artifactId>zuul-gateway-fallback</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>zuul-gateway-fallback</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Copy the code
4.3 Modifying the Configuration File
Spring. Application. Name =zuul-gateway-fallback server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
4.4 Adding the ProductFallbackProvider class
/** * Demote the product-provider */
@Component
public class ProductFallbackProvider implements ZuulFallbackProvider {

    /** * specifies which service to downgrade *@return* /
    @Override
    public String getRoute(a) {
        // Specify the name of the service to degrade
        return "ego-product-provider";
    }

    /** * This method returns the bottom content * when the service cannot be executed@return* /
    @Override
    public ClientHttpResponse fallbackResponse(a) {
        return new ClientHttpResponse() {

            /** * ClientHttpResponse fallback status code, HttpStatus *@return
             * @throws IOException
             */
            @Override
            public HttpStatus getStatusCode(a) throws IOException {
                return HttpStatus.OK;
            }

            /** * ClientHttpResponse fallback status code, int *@return
             * @throws IOException
             */
            @Override
            public int getRawStatusCode(a) throws IOException {
                return getStatusCode().value();
            }

            /** * The status code of the ClientHttpResponse fallback@return
             * @throws IOException
             */
            @Override
            public String getStatusText(a) throws IOException {
                return getStatusCode().getReasonPhrase();
            }

            /** * Closes the response */
            @Override
            public void close(a) {}/** * gets the response body *@return
             * @throws IOException
             */
            @Override
            public InputStream getBody(a) throws IOException {
                String content = "Goods and services not available, please contact your administrator.";
                return new ByteArrayInputStream(content.getBytes());
            }

            /** * get the response header *@return* /
            @Override
            public HttpHeaders getHeaders(a) {
                HttpHeaders httpHeaders = new HttpHeaders();
                MediaType mediaType = new MediaType("application"."json", Charset.forName("utf-8"));
                httpHeaders.setContentType(mediaType);
                returnhttpHeaders; }}; }}Copy the code

Sixth, in the case of high concurrency, the gateway realizes traffic limiting to achieve self-protection

1. Create projects

2. Add coordinates

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13. RELEASE</version>
        <relativePath /> <! -- lookup parent from repository -->
    </parent>
    <groupId>com.luyi</groupId>
    <artifactId>zuul-gateway-ratelimit</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>zuul-gateway-ratelimit</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <! -- https://mvnrepository.com/artifact/com.marcosbarbero.cloud/spring-cloud-zuul-ratelimit -->
        <dependency>
            <groupId>com.marcosbarbero.cloud</groupId>
            <artifactId>spring-cloud-zuul-ratelimit</artifactId>
            <version>1.5.0. RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Copy the code

3. Modify the configuration file

3.1 Full restricted flow
Name =zuul-gateway-ratelimit server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ zuul.routes.ego-product-provider.path=/product/** zuul.routes.ego-product-provider.service-id=ego-product-provider # set zuul.ratelimit. Enabled =true # Set more than 3 requests within 60 seconds Zuul.ratelimit.default-policy. Limit =3 zuul.ratelimit.default-policy-refresh -interval=60 Other IP addresses zuul.ratelimit.default-policy-type =origin are not affectedCopy the code
3.2 test

3.3 Local current limiting
Name =zuul-gateway-ratelimit server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ zuul.routes.ego-product-provider.path=/product/** zuul.routes.ego-product-provider.service-id=ego-product-provider If the number of requests exceeds 3 within 60 seconds, the server will throw an exception. #zuul.ratelimit.default-policy. Limit =3 #zuul.ratelimit.default-policy. Refresh -interval=60 Zuul.ratelimit. Enabled =true # If the number of requests exceeds three within 60 seconds, the server will throw an exception. If the number of requests exceeds three within 60 seconds, the server will throw an exception. Can return to normal after 60 s request zuul. Ratelimit. Policies. The ego - the product - provider. Limit = 3 Zuul. Ratelimit. Policies. The ego - the product - provider. Refresh - interval = 60 # IP for current limiting, Does not affect the other IP zuul. Ratelimit. Policies. The ego - the product - provider. Type = originCopy the code

4. Traffic limiting parameters of the gateway

Zuul performance tuning: Layer 2 timeout tuning of the gateway

1. Create projects

2. Add coordinates

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13. RELEASE</version>
        <relativePath /> <! -- lookup parent from repository -->
    </parent>
    <groupId>com.luyi</groupId>
    <artifactId>zuul-gateway-timeout</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>zuul-gateway-timeout</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Copy the code

3. Modify the configuration file

Spring.application. Name =zuul-gateway-timeout server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ # the first layer hystrix timeout setting hystrix.com mand. Default. Execution. The isolation. The thread. TimeoutInMilliseconds = 8000 # second ribbon timeout Settings, 5s ribbon.ConnectTimeout=5000 by default.ReadTimeout=5000Copy the code

4. Timeout tuning diagram