转载

学习SpringCloud Zuul带你从0到1

学习SpringCloud Zuul带你从0到1

二、网关入门案例

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 :网关端口号/请求的服务名/访问的url

学习SpringCloud Zuul带你从0到1

三、路由器的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 通配符含义

?:匹配任意单个字符

*:匹配任意数量的任意字符,但是不能添加 /

**:匹配任意数量的任意字符

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/**
复制代码

四、自定义网关过滤器

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.过滤器类型

学习SpringCloud Zuul带你从0到1

3.Zuul请求的生命周期

学习SpringCloud Zuul带你从0到1

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 网关过滤器执行顺序演示

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;
    }
}

复制代码

AccessFilter2

/**
 * 执行顺序演示
 */
@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;
    }
}

复制代码
学习SpringCloud Zuul带你从0到1

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'}";
    }
}

复制代码

五、网关容错

1.zuul和hystrix无缝结合

在zuul的jar包中包含了hystrix的jar包。所以我们不需要在项目中添加hystrix的坐标。

2.访问网关服务的数据监控流

学习SpringCloud Zuul带你从0到1

3.启动dashboard-view服务监控健康状况

学习SpringCloud Zuul带你从0到1

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;
            }
        };
    }
}

复制代码

六、在高并发情况下网关实现限流达到自我保护

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 测试

学习SpringCloud Zuul带你从0到1

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.网关限流参数

学习SpringCloud Zuul带你从0到1

七、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

复制代码
原文  https://juejin.im/post/5dd0a7275188252ad04c4f2d
正文到此结束
Loading...