spring-cloud-starter-netflix-zuul(原spring-cloud-starter-zuul)的使用-程序员宅基地

技术标签: spring boot  java  gateway  

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-程序员宅基地    请求重试配置参考 为Spring Cloud Ribbon/Zuul配置请求重试 - 简书

              3.2 hystrix(熔断器)com.netflix.hystrix.HystrixCommandProperties 参考hystrix参数详解-程序员宅基地     使用参考 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);"-程序员宅基地

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/name_is_wl/article/details/88890651

智能推荐

Ubuntu14.04 64bit 编译安装nginx1.7+php5.4+mysql5.6-程序员宅基地

文章浏览阅读88次。我的操作系统是Ubuntu14.04,其它linux系统的操作流程类似。主要安装的软件是nginx1.7+php5.4+mysql5.6 1. 创建必要目录sudo mkdir ~/setupsudo mkdir /opt/softwaresudo chmod 777 /opt/software 2. 下载必要软件cd ~/Downloads..._pcredairkitsetupexe

ubuntu compiz的问题 两种解决方法 (第一种貌似重启了无效)_sudo compiz 错误-程序员宅基地

文章浏览阅读8.4k次,点赞4次,收藏6次。compiz的问题 两种解决方法 (第一种貌似重启了无效)(1)sudo apt-get purge compizsudo apt-get install unity ubuntu-desktop(2)sudo apt-get remove unitysudo apt-get update && sudo apt-get upgradesudo apt-get_sudo compiz 错误

Python下Flask-ApScheduler快速指南_flask flask_apscheduler 网页地址-程序员宅基地

文章浏览阅读2.1w次。引言:Flask是Python社区非常流行的一个Web开发框架,本文将尝试将介绍APScheduler应用于Flask之中。_flask flask_apscheduler 网页地址

XS9950 :一路工规AHD模拟RX-程序员宅基地

文章浏览阅读700次。一路AHD转mipi/BT656_xs9950

Maven 项目 JDK 8、JDK 17 多版本 Java 编译依赖最佳实践_让maven环境 主动编译jdk17-程序员宅基地

文章浏览阅读782次,点赞13次,收藏19次。最近几年,整个 Java 生态圈正在经历并将长期出于从 JDK 8 到 JDK 17 或更高版本的升级换代中,较为典型是:以 Spring 为代表的 Web 应用开发框架大多已经升级到了 JDK 17,而在大数据生态圈,Flink、Spark 还在使用 JDK 8,对于那些多模块的 Maven 项目,会出现不同的 Module 使用不同版本的 JDK 问题,这给构建这类项目造成了一些困难,本文简单梳理一下这一问题的解决方法,给出最佳实践。_让maven环境 主动编译jdk17

NeurIPS 2023 | FedFed:特征蒸馏应对联邦学习中的数据异构-程序员宅基地

文章浏览阅读75次。作者 |杨智钦单位 |北京航空航天大学来源|将门创投在本文中,我们提出了一种新的即插即用的联邦学习模块,FedFed,其能够以特征蒸馏的方式来解决联邦场景下的数据异构问题。FedFed首次探索了对数据中部分特征的提取与分享,大量的实验显示,FedFed能够显著地提升联邦学习在异构数据场景下的性能和收敛速度。论文标题:FedFed: Feature Distillation against..._about [neurips 2023] "fedfed: feature distillation against data heterogeneit

随便推点

tomcat无法访问MySQL_JSP在tomcat服务器下无法连接MySql问题解决方法-程序员宅基地

文章浏览阅读1k次。我连的是MySQL数据库,但是在服务器下运行jsp文件时会出现如下的状况:控制台报错:com.mysql.jdbc.Driver即不能找到驱动程序,通过我的一次次试验,终于得到解决首先我的代码编写是没有问题的,而且我已经在eclipse下的jar库中导入了jdbc驱动文件。直接运行java应用程序运行java应用程序,结果如图所示,成功连接上数据库并打印输出了teacher表中所有数据。jsp中的..._tomcat对于jsp操作mysql数据库在页面不显示的问

Angular cdk 学习之 drag-drop_angular drag-drop-程序员宅基地

文章浏览阅读1w次,点赞5次,收藏10次。&nbsp; &nbsp; &nbsp; &nbsp;Angualr drag-drop里面的功能能让我们非常方便的处理页面上视图的拖拽(自由拖拽、列表排序拖拽、列表之间拖拽)问题。推荐大伙儿直接看官网,因为下面的内容绝大部分内容包括例子都来源于官网 https://material.angular.io/cdk/drag-drop/overview。一直认为官网才是最好的文档。&nbsp; &..._angular drag-drop

Android boot.img 结构_mkbootimg --base 0x00200000-程序员宅基地

文章浏览阅读678次。转自:http://www.linuxidc.com/Linux/2011-03/33303.htmAndroid 的boot.img 包括 boot header,kernel, ramdisk首先来看看Makefile是如何产生我们的boot.img的:boot镜像不是普通意义上的文件系统,而是一种特殊的Android定制格式,由boot header,压缩的内核,ramdisk以_mkbootimg --base 0x00200000

gitlab-runner安装注册_linux gitlab-runner shared specifc-程序员宅基地

文章浏览阅读1.3k次。# gitlab-runner registerRuntime platform arch=amd64 os=linux pid=28542 revision=8fa89735 version=13.6.0Running in system-mode. Enter the..._linux gitlab-runner shared specifc

Postgres-XL安装测试简单记录_error: `flex' is missing on your system-程序员宅基地

文章浏览阅读1.3k次。./configure --prefix=/vg/wonders/wonders/db/postgresql/pgxlmake make install cd contrib/ make make install编译好之后拖到一体机报错:ERROR: `flex' is missing on your system. It is needed to create thefile..._error: `flex' is missing on your system

vs2019安装和使用教程(详细)-程序员宅基地

文章浏览阅读10w+次,点赞565次,收藏2.9k次。vs2019安装和使用教程(详细)_vs2019

推荐文章

热门文章

相关标签