1.基于eureka为服务注册中心的zuul。

首先我们需要搭建一个eureka服务,关于这一步可以参考我的另一篇文章spring-cloud-eureka服务发现注册中心及spring-cloud微服务,在本篇文章也会用到spring-cloud-eureka服务发现注册中心及spring-cloud微服务里面的工程

下面我们新建zuul工程

<groupId>com.wl.springcloud</groupId>
<artifactId>zuul</artifactId>
<version>1.0-SNAPSHOT</version>

pom.xml(注意版本依赖,如果版本冲突,很有可能启动失败)

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wl.springcloud</groupId>
  <artifactId>zuul</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>zuul</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring-cloud-config-version>2.0.3.RELEASE</spring-cloud-config-version>
    <spring-cloud-eureka-server>2.0.3.RELEASE</spring-cloud-eureka-server>
    <spring-boot-version>2.0.8.RELEASE</spring-boot-version>
    <spring-cloud-zuul-version>2.0.3.RELEASE</spring-cloud-zuul-version>

    <spring-cloud-eureka-client-version>2.0.3.RELEASE</spring-cloud-eureka-client-version>
    <MainClass>com.wl.springcloud.zuul.ZuulApplication</MainClass>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      <version>${spring-cloud-eureka-client-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-config</artifactId>
      <version>${spring-cloud-config-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-zuul -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
      <version>${spring-cloud-zuul-version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version>${spring-boot-version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <!-- Package as an executable jar -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${spring-boot-version}</version>
        <configuration>
          <mainClass>${MainClass}</mainClass>
          <layout>JAR</layout>
        </configuration>
        <!-- repackage  生成两个 jar.original -->
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <!-- 指定maven 打包java 版本 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    <!-- maven  编译打包resource 和 java 目录下所有文件  maven默认资源路径是resources -->
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.*</include>
          <include>*.*</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.*</include>
          <include>*.*</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

application.properties

server.port=8080
spring.application.name=zuul

zuul.routes.consume.path=/consume/**
zuul.routes.consume.url=consume-client
#zuul.routes.consume.url=http://localhost:8763
#zuul.routes.consume.serviceId=consume-client
zuul.routes.consume.stripPrefix=false

zuul.routes.provider.path=/provider/**
zuul.routes.provider.url=provider-client
#zuul.routes.provider.url=http://localhost:8764
#zuul.routes.provider.serviceId=provider-client
zuul.routes.provider.stripPrefix=false

1.zuul.routes.consume.path、zuul.routes.provider.path中consume和provider可以为任意的字符,只是作为一个标识。/consume/** 表示代理路径为 /consume/**的路径并转发到serviceId为consume-client的服务

2.zuul.routes.consume.url 可以是全路径也可以是serviceId,这里配置的为服务id(即spring.application.name对应的值),与zuul.routes.consume.serviceId=consume-client效果一样

3.zuul.routes.provider.stripPrefix 表示是否匹配去掉前缀(默认为true),即所有/consume/**的请求转发到consume-client服务中的路径是否去掉consume。也就是所有/consume/xxxx的请求转发给http://consume.com.cn/xxxx ,去除掉consume前缀

启动类

package com.wl.springcloud.zuul;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

/**
 * Created by Administrator on 2019/3/28.
 */
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class,             //不使用数据库
        GsonAutoConfiguration.class                      //spring-boot2.0.0以上版本需要引入高版本的gson依赖,如果不引用gson依赖需要加此属性
},scanBasePackages = "com.wl")
@EnableZuulProxy
public class ZuulApplication {
    private static final Logger logger = LoggerFactory.getLogger(ZuulApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ZuulApplication.class);
        app.setWebApplicationType(WebApplicationType.SERVLET);
        app.run(args);
        logger.info("application init success");
    }

}

依次启动eureka、provider-client、consume-client、zuul

下面我们分别访问http://localhost:8080/consume/ 、http://localhost:8080/provider/

 2.基于zookeeper作为服务注册与发现中心的zuul的使用

使用zookeeper作为服务注册中心参考我的这篇文章spring-cloud使用zookeeper作为服务注册发现中心(下面会使用到该文章所建工程)

修改zuul工程的pom.xml如下(加入spring-cloud-starter-zookeeper-discovery依赖,移除spring-cloud-starter-netflix-eureka-client依赖)

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wl.springcloud</groupId>
  <artifactId>zuul</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>zuul</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring-cloud-config-version>2.0.3.RELEASE</spring-cloud-config-version>
    <spring-cloud-eureka-server>2.0.3.RELEASE</spring-cloud-eureka-server>
    <spring-boot-version>2.0.8.RELEASE</spring-boot-version>
    <spring-cloud-zuul-version>2.0.3.RELEASE</spring-cloud-zuul-version>

    <spring-cloud-eureka-client-version>2.0.3.RELEASE</spring-cloud-eureka-client-version>
    <MainClass>com.wl.springcloud.zuul.ZuulApplication</MainClass>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
    <!--<dependency>-->
      <!--<groupId>org.springframework.cloud</groupId>-->
      <!--<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
      <!--<version>${spring-cloud-eureka-client-version}</version>-->
    <!--</dependency>-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-config</artifactId>
      <version>${spring-cloud-config-version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
      <version>2.0.0.RELEASE</version>
      <exclusions>
        <exclusion>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.zookeeper</groupId>
          <artifactId>zookeeper</artifactId>
        </exclusion>

      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.10</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-zuul -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
      <version>${spring-cloud-zuul-version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version>${spring-boot-version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <!-- Package as an executable jar -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${spring-boot-version}</version>
        <configuration>
          <mainClass>${MainClass}</mainClass>
          <layout>JAR</layout>
        </configuration>
        <!-- repackage  生成两个 jar.original -->
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <!-- 指定maven 打包java 版本 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    <!-- maven  编译打包resource 和 java 目录下所有文件  maven默认资源路径是resources -->
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.*</include>
          <include>*.*</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.*</include>
          <include>*.*</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

修改配置文件如下

server.port=8080
spring.application.name=zuul

spring.cloud.zookeeper.connect-string=192.168.245.129:2181

zuul.routes.zookeeper.path=/zookeeper/**
zuul.routes.zookeeper.url=zookeeper
zuul.routes.zookeeper.stripPrefix=false

重启应用

浏览器输入http://localhost:8080/zookeeper/zookeeper

 3.spring-cloud客户端配置

              3.1 ribbon(负载均衡)  com.netflix.client.config.DefaultClientConfigImpl   参考Netflix学习笔记:Ribbon-CSDN博客    请求重试配置参考 为Spring Cloud Ribbon/Zuul配置请求重试 - 简书

              3.2 hystrix(熔断器)com.netflix.hystrix.HystrixCommandProperties 参考hystrix参数详解-CSDN博客     使用参考 https://www.cnblogs.com/yepei/p/7169127.html 与spring-boot整合参考 https://www.cnblogs.com/leeSmall/p/8847652.html   一行代码从Hystrix迁移到Sentinel参考Spring Cloud Alibaba迁移指南2:一行代码从Hystrix迁移到Sentinel - ITMuch的博客 - OSCHINA - 中文开源技术交流社区

              3.3 zuul配置  org.springframework.cloud.netflix.zuul.filters.ZuulProperties  参考使用Zuul构建API Gateway

4.zuul 过滤器

              4.1 异常拦截器 

                   org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter(forwards to /error (by default))

                   org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController(位于spring-boot-autoconfigure 包中)

                   配置

ribbon.ReadTimeout=1000

                   ZookeeperController修改如下

package com.wl.springcloud.zookeeper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2019/3/29.
 */
@RequestMapping("/zookeeper")
@RestController
public class ZookeeperController {

    @Autowired
    private Environment environment;

    @RequestMapping("/zookeeper")
    public String zookeeper() throws InterruptedException {
        Thread.sleep(1000L);
        return "zookeeper port:" + environment.getProperty("server.port");
    }
}

浏览器输入http://localhost:8080/zookeeper/zookeeper

BasicErrorController断点如下

自定义异常捕获

 方式一自定义ErrorController覆盖BasicErrorController

package com.wl.springcloud.zuul.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by Administrator on 2019/4/2.
 */
@Controller
public class ErrorController  implements org.springframework.boot.web.servlet.error.ErrorController {

    @Value(value = "${server.error.path:${error.path:/error}}")
    private String errorPath;

    @Override
    public String getErrorPath() {
        return errorPath;
    }

    private final ErrorAttributes errorAttributes;

    public ErrorController(ErrorAttributes errorAttributes){
        this.errorAttributes = errorAttributes;
    }

    @RequestMapping("${server.error.path:${error.path:/error}}")
    @ResponseBody
    public ResponseEntity error(HttpServletRequest request) {
        Map<String,Object> body = getErrorAttributes(request);
        body.put("code",1);
        body.remove("trace");
        return new ResponseEntity<>(body, HttpStatus.OK);
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        WebRequest webRequest = new ServletWebRequest(request);
        return this.errorAttributes.getErrorAttributes(webRequest, true);
    }

}

              

方式二 自定义SendErrorFilter

配置

zuul.SendErrorFilter.error.disable=true

filter

package com.wl.springcloud.zuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.client.ClientException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException;
import org.springframework.http.HttpStatus;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ERROR_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_ERROR_FILTER_ORDER;

/**
 * Created by Administrator on 2019/4/2.
 */
public class CusSendErrorFilter extends ZuulFilter {

    protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";

    @Value("${error.path:/error}")
    private String errorPath;


    @Override
    public String filterType() {
        return ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return SEND_ERROR_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        // only forward to errorPath if it hasn't been forwarded to already
        return ctx.getThrowable() != null
                && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false);
    }

    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            ExceptionHolder exception = findZuulException(ctx.getThrowable());
            HttpServletResponse response = ctx.getResponse();
            Map<String,Object> body = new HashMap<>();
            body.put("code",1);
            body.put("status",exception.getStatusCode());
            body.put("msg",exception.getErrorCause());
            response.setContentType("application/json; charset=utf8");
            response.setStatus(HttpStatus.OK.value());

            response.getWriter().write(new ObjectMapper().writeValueAsString(body));
        }
        catch (Exception ex) {
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }

    protected ExceptionHolder findZuulException(Throwable throwable) {
        if (throwable.getCause() instanceof ZuulRuntimeException) {
            Throwable cause = null;
            if (throwable.getCause().getCause() != null) {
                cause = throwable.getCause().getCause().getCause();
            }
            if (cause instanceof ClientException && cause.getCause() != null
                    && cause.getCause().getCause() instanceof SocketTimeoutException) {

                ZuulException zuulException = new ZuulException("", 504,
                        ZuulException.class.getName() + ": Hystrix Readed time out");
                return new ZuulExceptionHolder(zuulException);
            }
            // this was a failure initiated by one of the local filters
            if(throwable.getCause().getCause() instanceof ZuulException) {
                return new ZuulExceptionHolder((ZuulException) throwable.getCause().getCause());
            }
        }

        if (throwable.getCause() instanceof ZuulException) {
            // wrapped zuul exception
            return  new ZuulExceptionHolder((ZuulException) throwable.getCause());
        }

        if (throwable instanceof ZuulException) {
            // exception thrown by zuul lifecycle
            return new ZuulExceptionHolder((ZuulException) throwable);
        }

        // fallback
        return new DefaultExceptionHolder(throwable);
    }

    protected interface ExceptionHolder {
        Throwable getThrowable();

        default int getStatusCode() {
            return HttpStatus.INTERNAL_SERVER_ERROR.value();
        }

        default String getErrorCause() {
            return null;
        }
    }

    protected static class DefaultExceptionHolder implements ExceptionHolder {
        private final Throwable throwable;

        public DefaultExceptionHolder(Throwable throwable) {
            this.throwable = throwable;
        }

        @Override
        public Throwable getThrowable() {
            return this.throwable;
        }
    }

    protected static class ZuulExceptionHolder implements ExceptionHolder {
        private final ZuulException exception;

        public ZuulExceptionHolder(ZuulException exception) {
            this.exception = exception;
        }

        @Override
        public Throwable getThrowable() {
            return this.exception;
        }

        @Override
        public int getStatusCode() {
            return this.exception.nStatusCode;
        }

        @Override
        public String getErrorCause() {
            return this.exception.errorCause;
        }
    }
}

 config

package com.wl.springcloud.zuul.config;

import com.wl.springcloud.zuul.filter.CusSendErrorFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by Administrator on 2019/4/2.
 */
@Configuration
public class FilterConfig {


    @Bean
    public CusSendErrorFilter cusSendErrorFilter(){
        return new CusSendErrorFilter();
    }

}

4.2 自定义过滤器

package com.wl.springcloud.zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2019/4/2.
 */
public class CusZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * a "true" return from this method means that the run() method should be invoked
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        return uri.contains("/service/");          //请求路径包含/service/的会被拦截
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        Object object = request.getSession().getAttribute("USER");
        if(object != null){
            requestContext.setSendZuulResponse(true);//会进行路由,也就是会调用api服务提供者
            requestContext.setResponseStatusCode(HttpStatus.OK.value());
            requestContext.set("isOK",true);// 相当于设置上下文的key-value键值对  requestContext(请求上下文)可以通过requestContext.get获取
            boolean b = (boolean) requestContext.get("isOK");
            System.out.println(b);
        }else{
            requestContext.setSendZuulResponse(false);    //不会调用下级服务   直接在网关返回
            requestContext.setResponseStatusCode(HttpStatus.OK.value());
            Map<String,Object> body = new HashMap<>();
            body.put("code",1);
            body.put("msg","session is closed please login again");

            //设置响应头信息 Content-Type
            requestContext.addZuulResponseHeader("Content-Type","application/json");
            try {
                requestContext.setResponseBody(new ObjectMapper().writeValueAsString(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

package com.wl.springcloud.zuul.config;

import com.wl.springcloud.zuul.filter.CusSendErrorFilter;
import com.wl.springcloud.zuul.filter.CusZuulFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by Administrator on 2019/4/2.
 */
@Configuration
public class FilterConfig {


    @Bean
    public CusSendErrorFilter cusSendErrorFilter(){
        return new CusSendErrorFilter();
    }

    @Bean
    public CusZuulFilter cusZuulFilter(){
        return new CusZuulFilter();
    }

}

浏览器地址输入 http://localhost:8080/zookeeper/zookeeper/service/

在zuul返回响应结果之前都会执行SendResponseFilter过滤器(除非直接调用response.write或关闭该拦截器)

更多过滤器在spring-cloud-starter-netflix-zuul jar包中org.springframework.cloud.netflix.zuul.filters包下面

自定义过滤器参考 springCloud学习05之api网关服务zuul过滤器filter_"ctx.set(\"isok\", false);"-CSDN博客

5.zuul跨域

package com.wl.springcloud.zuul.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;
import java.util.Set;

/**
 * Created by Administrator on 2019/4/2.
 */
@Configuration
public class CorsConfig {

    @Bean
    public FilterRegistrationBean<CorsFilter> filterRegistrationBean(ZuulProperties zuulProperties){
        //需要过滤的下游头信息  可以配置zuul.sensitiveHeaders  zuul.ignoredHeaders  参考 https://blog.csdn.net/ahutdbx/article/details/84192573
        Set<String> ignoredHeaders = zuulProperties.getIgnoredHeaders();
        ignoredHeaders.add("ga");
        zuulProperties.setIgnoredHeaders(ignoredHeaders);
        //跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        //设置网站域名  *表示全部
        corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
        //设置允许的头  *表示全部
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        //设置允许的方法 *表示全部
        corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        // Set the order of the registration bean.  越小越排前面
        bean.setOrder(0);
        return bean;
    }

}

6.zuul服务降级

package com.wl.springcloud.zuul.fallback;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2019/5/24.
 */
@Component
public class ZuulFallback implements FallbackProvider {

    @Override
    public String getRoute() {
        return "*";//*表示匹配所有路由
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        RequestContext.getCurrentContext().set("fallback",true);
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                Map<String,Object> body = new HashMap<>();
                body.put("code",1);
                body.put("msg",cause!= null ? cause.getMessage() : "");
                return new ByteArrayInputStream(new ObjectMapper().writeValueAsString(body).getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type","application/json");
                return headers;
            }
        };
    }
}

因为下游服务异常也可能会走之前设置的自定义异常过滤器,这里我设置了一个标识RequestContext.getCurrentContext().set("fallback",true);

修改之前自定义的异常过滤器,如果服务降级则不经过自定义异常过滤器(直接通过默认的SendResposeFiltrer返回响应数据)

@Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        // only forward to errorPath if it hasn't been forwarded to already
        return ctx.getThrowable() != null
                && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false)
                && !ctx.getBoolean("fallback",false);
    }

启动zuul并关闭下游服务

浏览器输入http://localhost:8080/zookeeper/zookeeper

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐