學習SpringCloud Zuul帶你從0到1

1、爲何要使用網關

2、網關入門案例

1.建立項目

1.1 添加座標
<?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-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>
1,2 修改配置文件
spring.application.name=zuul-gateway
server.port=9020

#設置服務註冊中心地址,向全部註冊中心作註冊
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
1.3 修改啓動類
//開啓網關代理
@EnableZuulProxy
@SpringBootApplication
public class ZuulApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class, args);
    }
}
1.4 經過網關請求服務

訪問:http://IP:網關端口號/請求的服務名/訪問的urlhtml

3、路由器的4種路由規則方法

1.建立項目

2.採用URL指定路由方式

2.1 修改配置文件
spring.application.name=zuul-gateway-route
server.port=9030

#設置服務註冊中心地址,向全部註冊中心作註冊
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/

#1.路由指定:URL指定
#URL指定關鍵字,若是包含關鍵字就跳轉到指定的URL中
zuul.routes.ego-product-provider.path=/ego-product-provider/**
zuul.routes.ego-product-provider.url=http://127.0.0.1:9001/
2.2 通配符含義

?:匹配任意單個字符java

*:匹配任意數量的任意字符,可是不能添加 / web

**:匹配任意數量的任意字符redis

3.採用服務指定路由方式

#2.路由指定:服務指定1
#將路徑的/suibian/引到 eureka的 ego-product-provider 服務上
#規則:zuul.routes.路徑名.path
#規則:zuul.routes.路徑名.serviceId=eureka的服務名
#zuul.routes.ego-product-provider.path=/suibian/**
#zuul.routes.ego-product-provider.service-id=ego-product-provider

#3.路由指定:服務指定2
#zuul.routes後面跟着的是服務名,服務名後面跟着的是路徑規則,這種配置方式更簡單。
zuul.routes.ego-product-provider.path=/suibian/**

4.路由的排除法

#4.路由排除:排除某幾個服務
#排除後,這個地址將爲空, http://127.0.0.1:9030/ego-product-provider/product/findAll
#多個服務使用逗號分開
#zuul.ignored-services=ego-product-provider

#5.路由排除:排除全部服務
#因爲路由太多,不可能所有手動添加,故路由排除全部服務,而後針對要路由的服務進行手動添加
#zuul.ignored-services=*
#zuul.routes.ego-product-provider=/ego-product-provider/**

#6.路由排除:排除指定關鍵字的路徑
#排除全部包括/list/的路徑
#zuul.ignored-patterns=/**/findAll/**
zuul.routes.ego-product-provider.path=/ego-product-provider/**

5.路由的添加前綴方法

#7.路由添加前綴:爲全部路徑添加前綴
#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.ego-product-provider.path=/suibian/**

4、自定義網關過濾器

1.編寫網關過濾器

1.1 建立項目
1.2 添加座標
<?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-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>
1.3 修改配置文件
spring.application.name=zuul-gateway-filter
server.port=9020

#設置服務註冊中心地址,向全部註冊中心作註冊
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
1.4 編寫filter
@Component
public class LogFilter extends ZuulFilter {

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

    /**
     * 過濾器類型,經過過濾器類型決定了過濾器執行的時機
     * @return
     */
    @Override
    public String filterType() {
        //在路由以前執行
        return "pre";
    }

    /**
     * 過濾器的執行順序:經過返回的整數表示順序,數值越小優先級越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否開啓過濾器,默認爲false
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 過濾內容:在run方法中編寫過濾邏輯
     * @return
     */
    @Override
    public Object run() {
        //獲取請求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //獲取請求方式
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("LogFilter...method={},url={}", request.getMethod(), request.getRequestURL().toString());
        return null;
    }
}
1.5 修改啓動類
//開啓網關代理
@EnableZuulProxy
@SpringBootApplication
public class ZuulApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class, args);
    }
}

2.過濾器類型

3.Zuul請求的生命週期

4.採用網關過濾器實現權限驗證

需求:在網關過濾器中經過Token判斷用戶是否登陸
4.1 建立項目
4.2 添加座標
<?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-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>
4.3 修改配置文件
spring.application.name=zuul-gateway-example
server.port=9020

#設置服務註冊中心地址,向全部註冊中心作註冊
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
4.4 建立AccessFilter
/**
 * 登陸權限驗證
 */
@Component
public class AccessFilter extends ZuulFilter {

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

    /**
     * 過濾器類型,經過過濾器類型決定了過濾器執行的時機
     * @return
     */
    @Override
    public String filterType() {
        //在路由以前執行
        return "pre";
    }

    /**
     * 過濾器的執行順序:經過返回的整數表示順序,數值越小優先級越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否開啓過濾器,默認爲false
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 過濾內容:在run方法中編寫過濾邏輯
     * @return
     */
    @Override
    public Object run() {
        //獲取請求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //獲取請求方式
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------pre1------------------------");
        //獲取表單中的token
        String token = request.getParameter("token");
        //對token作判斷
        if (token == null){
            LOGGER.warn("token is null.");
            requestContext.setSendZuulResponse(false);  //表明請求結束,再也不繼續向下請求
            //表示沒有token
            requestContext.setResponseStatusCode(401);
            //響應內容
            requestContext.setResponseBody("{'result':'token is null.'}");
            //響應類型
            requestContext.getResponse().setContentType("text/html;charset=utf-8");
        }else{
            //訪問redis服務進行驗證
            LOGGER.info("token is ok.");
        }
        return null;
    }
}

5.網關過濾器執行順序與post類型演示

5.1 網關過濾器執行順序演示

AccessFilterspring

/**
 * 執行順序演示
 */
@Component
public class AccessFilter extends ZuulFilter {

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

    /**
     * 過濾器類型,經過過濾器類型決定了過濾器執行的時機
     * @return
     */
    @Override
    public String filterType() {
        //在路由以前執行
        return "pre";
    }

    /**
     * 過濾器的執行順序:經過返回的整數表示順序,數值越小優先級越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否開啓過濾器,默認爲false
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 過濾內容:在run方法中編寫過濾邏輯
     * @return
     */
    @Override
    public Object run() {
        //獲取請求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //獲取請求方式
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------pre1------------------------");
        //獲取表單中的token
        String token = request.getParameter("token");
        //對token作判斷
        if (token == null){
            LOGGER.warn("token is null.");
            requestContext.setSendZuulResponse(false);  //表明請求結束,再也不繼續向下請求
            //表示沒有token
            requestContext.setResponseStatusCode(401);
            //響應內容
            requestContext.setResponseBody("{'result':'token is null.'}");
            //響應類型
            requestContext.getResponse().setContentType("text/html;charset=utf-8");
        }else{
            //訪問redis服務進行驗證
            LOGGER.info("token is ok.");
        }
        return null;
    }
}

AccessFilter2apache

/**
 * 執行順序演示
 */
@Component
public class AccessFilter2 extends ZuulFilter {

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

    /**
     * 過濾器類型,經過過濾器類型決定了過濾器執行的時機
     * @return
     */
    @Override
    public String filterType() {
        //在路由以前執行
        return "pre";
    }

    /**
     * 過濾器的執行順序:經過返回的整數表示順序,數值越小優先級越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 是否開啓過濾器,默認爲false
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 過濾內容:在run方法中編寫過濾邏輯
     * @return
     */
    @Override
    public Object run() {
        //獲取請求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //獲取請求方式
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------pre2------------------------");

        return null;
    }
}

5.2 post類型演示
/**
 * post類型演示
 */
@Component
public class PostFilter extends ZuulFilter {

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

    /**
     * 過濾器類型,經過過濾器類型決定了過濾器執行的時機
     * @return
     */
    @Override
    public String filterType() {
        return "post";
    }
    
    /**
     * 過濾器的執行順序:經過返回的整數表示順序,數值越小優先級越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否開啓過濾器,默認爲false
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 過濾內容:在run方法中編寫過濾邏輯
     * @return
     */
    @Override
    public Object run() {
        //獲取請求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //獲取請求方式
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------post------------------------");
        return null;
    }
}

6.採用網關過濾器對異常進行統一處理

6.1 建立 ErrorFilter
/**
 * error類型演示
 */
@Component
public class ErrorFilter extends ZuulFilter {

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

    /**
     * 過濾器類型,經過過濾器類型決定了過濾器執行的時機
     * @return
     */
    @Override
    public String filterType() {
        return "error";
    }

    /**
     * 過濾器的執行順序:經過返回的整數表示順序,數值越小優先級越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 是否開啓過濾器,默認爲false
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 過濾內容:在run方法中編寫過濾邏輯
     * @return
     */
    @Override
    public Object run() {
        //獲取請求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //獲取請求方式
        HttpServletRequest request = requestContext.getRequest();
        LOGGER.info("------------------error------------------------");

        return null;
    }
}
6.2 建立ExceptionHandler
/**
 * 對異常響應內容處理
 */
@RestController
public class ExceptionHandler implements ErrorController {
    @Override
    public String getErrorPath() {
        return "/error";
    }

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

5、網關容錯

1.zuul和hystrix無縫結合

在zuul的jar包中包含了hystrix的jar包。因此咱們不須要在項目中添加hystrix的座標。json

2.訪問網關服務的數據監控流

3.啓動dashboard-view服務監控健康情況

4.在網關中實現對服務的降級處理

4.1 建立項目
4.2 添加座標
<?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-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>
4.3 修改配置文件
spring.application.name=zuul-gateway-fallback
server.port=9020

#設置服務註冊中心地址,向全部註冊中心作註冊
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
4.4 添加ProductFallbackProvider類
/**
 * 對Product-Provider作降級處理
 */
@Component
public class ProductFallbackProvider implements ZuulFallbackProvider {

    /**
     * 給定對哪一個服務作降級處理
     * @return
     */
    @Override
    public String getRoute() {
        //指定作降級的服務名
        return "ego-product-provider";
    }

    /**
     * 服務沒法執行時,該方法返回託底內容
     * @return
     */
    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {

            /**
             * ClientHttpResponse的fallback的狀態碼,HttpStatus類型
             * @return
             * @throws IOException
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            /**
             * ClientHttpResponse的fallback的狀態碼,int類型
             * @return
             * @throws IOException
             */
            @Override
            public int getRawStatusCode() throws IOException {
                return getStatusCode().value();
            }

            /**
             * ClientHttpResponse的fallback的狀態碼,String類型
             * @return
             * @throws IOException
             */
            @Override
            public String getStatusText() throws IOException {
                return getStatusCode().getReasonPhrase();
            }

            /**
             * 關閉響應
             */
            @Override
            public void close() {

            }

            /**
             * 獲取響應體
             * @return
             * @throws IOException
             */
            @Override
            public InputStream getBody() throws IOException {
                String content = "商品服務不可用,請與管理員聯繫";
                return new ByteArrayInputStream(content.getBytes());
            }

            /**
             * 獲取響應頭
             * @return
             */
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                MediaType mediaType = new MediaType("application", "json", Charset.forName("utf-8"));
                httpHeaders.setContentType(mediaType);
                return httpHeaders;
            }
        };
    }
}

6、在高併發狀況下網關實現限流達到自我保護

1.建立項目

2.添加座標

<?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-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>

3.修改配置文件

3.1 全侷限流
spring.application.name=zuul-gateway-ratelimit
server.port=9020

#設置服務註冊中心地址,向全部註冊中心作註冊
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

#全局配置限流
zuul.ratelimit.enabled=true
#60s內超過3次請求服務端就拋出異常,60s後能夠恢復正常請求
zuul.ratelimit.default-policy.limit=3
zuul.ratelimit.default-policy.refresh-interval=60
#針對IP進行限流,不影響其餘IP
zuul.ratelimit.default-policy.type=origin
3.2 測試

3.3 局部限流
spring.application.name=zuul-gateway-ratelimit
server.port=9020

#設置服務註冊中心地址,向全部註冊中心作註冊
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

#全局配置限流
#zuul.ratelimit.enabled=true
##60s內超過3次請求服務端就拋出異常,60s後能夠恢復正常請求
#zuul.ratelimit.default-policy.limit=3
#zuul.ratelimit.default-policy.refresh-interval=60
##針對IP進行限流,不影響其餘IP
#zuul.ratelimit.default-policy.type=origin

#局部限流,針對某個服務進行限流
zuul.ratelimit.enabled=true
#60s內超過3次請求服務端就拋出異常,60s後能夠恢復正常請求
zuul.ratelimit.policies.ego-product-provider.limit=3
zuul.ratelimit.policies.ego-product-provider.refresh-interval=60
#針對IP進行限流,不影響其餘IP
zuul.ratelimit.policies.ego-product-provider.type=origin

4.網關限流參數

7、zuul性能調優:網關的2層超時調優

1.建立項目

2.添加座標

<?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-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>

3.修改配置文件

spring.application.name=zuul-gateway-timeout
server.port=9020

#設置服務註冊中心地址,向全部註冊中心作註冊
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/

#第一層hystrix超時時間設置
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=8000

#第二層ribbon超時時間設置,設置的比第一層小
#鏈接超時時間,默認5s
ribbon.ConnectTimeout=5000
#請求處理的超時時間,默認5s
ribbon.ReadTimeout=5000

4.超時調優圖解

相關文章
相關標籤/搜索