Spring程序员Java学习笔记

Spring Cloud:服务网关 Zuul

2018-03-09  本文已影响665人  聪明的奇瑞

为什么要使用微服务网关

Zuul简介

若要使用 RestClient 可设置

ribbon.restclient.enabled = true

若要使用 okhttp3.OKHttpClient 可设置

ribbon.okhttp.enabled = true

编写Zuul微服务网关

创建新项目,添加zuul依赖库

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

在启动类添加注解 @EnableZuulProxy,声明一个 Zuul 代理,该代理用 Ribbon 来定位 Eureka Server 中的微服务,同时整合了 Hystrix,实现了容错

编写配置文件

server:
    port: 8040
spring:
    application:
        name: zuul
eureka:
    client:
        service-url:
            defaultZone: http://localhost:8761/eureka/

测试

Zuul 路由端点

路由配置

指定微服务访问路径,配置 zuul.routes.微服务的 serviceId = 指定路径,当访问 /user/** 时会转发到微服务 flim-user

zuul:
    routes:
        flim-user: /user/**

忽略指定微服务,通过 zuul.ignored-services 配置需要忽略的微服务,多个微服务通过逗号隔开

zuul:
    ignored-services: flim-user,flim-consumer

忽略所有微服务,只路由指定微服务

zuul:
    ignored-services:'*'  #使用'*'忽略所有微服务
    routes:
        flim-user: /user/**

指定微服务的 serviceId 和对应路径

zuul:
    routes:
        user-route:     #该配置方式中,user-route 只是给路由起的一个名称,可以任意起名
            service-id: provider-flim-user
            path: /user/**

指定 path 和 URL,但会破坏 Ribbon 负载均衡和 HystrixCommand 执行

zuul:
    routes:
        user-route:     #该配置方式中,user-route 只是给路由起的一个名称,可以任意起名
            url: http://localhost:8000/
            path: /user/**

指定 path 和 URL,不会破坏 Ribbon、Hystrix 特性

zuul:
    routes:
        user-route:     #该配置方式中,user-route 只是给路由起的一个名称,可以任意起名
            service-id: flim-user
            path: /user/**
ribbon:
    eureka:
        enabled: false  #为Ribbon禁用Eureka
flim-user:
    ribbon:
        listOfServers: localhost:8000,localhost:8001

借助 PatternServiceRouteMapper 使用正则表达式匹配路由

@Bean 
public PatternServiceRouteMapper serviceRouteMapper(){
    // 调用构造函数 PatternServiceRouteMapper(String servicePattern,String routePattern)
    // servicePattern 指定微服务的正则
    // routePattern 指定路由正则
    return new PatternServiceRouteMapper("(?<name>^.+)-(?<version>v.+$)","${version}/${name}");
}

路由前缀

#将 /api/flim-user/1 的请求转发到 flim-user 的 /api/1
zuul:
    prefix: /api
    strip-prefix: false
    routes:
        flim-user: /user/**
#将 /user/1 请求转发到 flim-user 的 /user/1
zuul:
    routes:
        flim-user:
            path: /user/**
            strip-prefix: false

忽略某些路径,通过正则匹配

zuul:
    ignoredPatterns:/**/admin/**  #忽略所有包含 /admin/ 的路径
    routes:
        flim-user: /user/**

Zuul 安全与 Header

敏感的 Header 设置

zuul:
    routes:
        flim-user:
            ptah: /user/**
            sensitive-headers: Cookie,Set-Cookie,Authorization
            url: https://downstream
zuul:
    sensitive-headers: Cookie,Set-Cookie,Authorization

忽略 Header

zuul:
    ignored-headers: Header1,Header2

使用 Zuul 上传文件

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
    ConnectTimeout: 3000
    ReadTimeout: 60000

编写文件上传微服务

创建新项目 file-upload,并添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

在启动类上添加 @EnableEurekaClient
编写 Controller

@RestController
public class FileUploadController {
    @PostMapping(name = "/upload")
    public String handleFileUpLoad(@RequestParam(value = "file") MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        File fileToSave = new File(file.getOriginalFilename());
        FileCopyUtils.copy(bytes, fileToSave);
        return fileToSave.getAbsolutePath();
    }
}

编写配置文件

server:
  port: 8050
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
    instance:
      prefer-ip-address: true
spring:
  application:
    name: file-upload
  http:
    multipart:
      max-file-size: 2000Mb
      max-request-size: 2500Mb

测试

There was an unexpected error (type=Internal Server Error, status=500).
Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (155106628) exceeds the configured maximum (10485760)
There was an unexpected error (type=Internal Server Error, status=500).
TIMEOUT
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
    ConnectTimeout: 3000
    ReadTimeout: 60000

Zuul 过滤器

编写 Zuul 过滤器

创建过滤器类,继承抽象类 ZuulFilter 并实现抽象方法

/**
 * @description: Zuul日志过滤器
 * filterType:返回过滤器类型,有 pre、route、post、error 等几种取值
 * filterOrder:返回一个 int 值指定过滤器执行顺序,不同过滤器允许返回相同的数字
 * shouldFilter:true 表示过滤器执行、false表示不执行
 * run:过滤器具体逻辑,下面代码打印了请求方法和URL
 */
public class PreRequestLogFilter extends ZuulFilter{

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

    @Override
    public String filterType() {
        return "pre";
    }

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

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        PreRequestLogFilter.LOGGER.info(String.format("send %s request to %s",request.getMethod(),request.getRequestURL().toString()));
        return null;
    }
}

将过滤器通过 @Bean 注入到 IOC 容器

@Bean
public PreRequestLogFilter preRequestLogFilter() {
    return new PreRequestLogFilter();
}

测试

c.l.zuul.filter.PreRequestLogFilter      : send GET request to http://localhost:8040/flim-user/1

禁用 Zuul 过滤器

zuul.SendResponseFilter.post.disable = true

为 Zuul 添加回退

编写 Zuul 回退类

@Component
public class UserFallbackProvider implements ZuulFallbackProvider {

    @Override
    public String getRoute() {
        //表明为哪个微服务提供回退
        return "flim-user";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                //回退时的状态码
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                //数字类型的状态码,本文返回的是200
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                //状态文本,本文返回的是OK
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                //响应体
                return new ByteArrayInputStream("用户微服务不可用".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                //headers设定
                HttpHeaders httpHeaders = new HttpHeaders();
                MediaType mt = new MediaType("application","json", Charset.forName("UTF-8"));
                httpHeaders.setContentType(mt);
                return httpHeaders;
            }
        };
    }
}

测试

用户微服务不可用

Zuul 高可用

修改 ServiceId 与路由映射规则

@Bean
public PatternServiceRouteMapper serviceRouteMapper() {
    return new PatternServiceRouteMapper(
        "(?<name>^.+)-(?<version>.+$)",
        "${version}/${name}");
}

---- 待完善 ----

上一篇下一篇

猜你喜欢

热点阅读