Spring Cloud 微服务之Zuul(八)

22 篇文章 1 订阅
18 篇文章 0 订阅

一、什么是Spring Cloud Zuul?

  • Spring Cloud Zuul 是Spring Cloud Netflix 子项目的核心组件之一,可以作为微服务架构中的API网关使用,支持动态路由与过滤功能。
  • API网关为微服务架构中的服务提供了统一的访问入口,客户端通过API网关访问相关服务。
  • API网关的定义类似于设计模式中的门面模式,它相当于整个微服务架构中的门面,所有客户端的访问都通过它来进行路由及过滤。
  • API网关实现了请求路由、负载均衡、校验过滤、服务容错、服务聚合等功能。

二、案例演示

  • 添加依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    
  • 添加配置

    • 启动类

      @SpringBootApplication
      @EnableDiscoveryClient
      @EnableZuulProxy
      public class SpringcloudZuulApplication {
          public static void main(String[] args) {
              SpringApplication.run(SpringcloudZuulApplication.class, args);
          }
      }
      
    • application.yml配置文件

      server:
        port: 8888
        servlet:
          context-path: /
      
      spring:
        application:
          name: springcloud-zuul
      
      eureka:
        instance:
          instance-id: springcloud-zuul-8888
          prefer-ip-address: true
        client:
          register-with-eureka: true
          fetch-registry: true
          service-url:
            defaultZone: http://localhost:8010/eureka
      
  • 测试使用

    # 1.访问:http://localhost:8021/get/1
    {"msg":"查询成功","type":"ok","content":{"id":1,"username":"张三","password":"zhangsan"}}
    
    # 2.访问:http://localhost:8888/springcloud-service/get/1
    {"msg":"查询成功","type":"ok","content":{"id":1,"username":"张三","password":"zhangsan"}}
    

三、路由配置

  • 添加配置

    zuul:
      # 配置路由
      routes:
        springcloud-service:
          path: /userService/**
      # 过滤路由
      ignored-services: springcloud-service
      # 访问前缀
      prefix: /
      # 配置过滤敏感的请求头信息,设置为空就不会过滤
      sensitive-headers: Cookie,Set-Cookie,Authorization
      # 指定重定向是否要添加host请求头
      add-host-header: true
    
  • 测试使用

    # 1.访问:http://localhost:8021/get/1
    {"msg":"查询成功","type":"ok","content":{"id":1,"username":"张三","password":"zhangsan"}}
    
    # 2.不能访问:http://localhost:8888/springcloud-service/get/1
    
    # 3.访问:http://localhost:8888/userService/get/1
    {"msg":"查询成功","type":"ok","content":{"id":1,"username":"张三","password":"zhangsan"}}
    

四、路由信息

  • 添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  • 添加配置

    management:
      endpoints:
        web:
          exposure:
            include: 'routes'
    
  • 测试使用

    # 1.访问:http://localhost:8888/actuator/routes
    {"/userService/**":"springcloud-service"}
    
    # 2.访问:http://localhost:8888/actuator/routes/details
    {"/userService/**":{"id":"springcloud-service","fullPath":"/userService/**",...}
    

五、过滤器

过滤功能负责对请求过程进行额外的处理,是请求校验过滤及服务聚合的基础。

  • 过滤器类型

    • pre

      在请求被路由到目标服务前执行,比如权限校验、打印日志等功能

    • routing

      在请求被路由到目标服务时执行,这是使用Apache HttpClient或Netflix Ribbon构建和发送原始HTTP请求的地方

    • post

      在请求被路由到目标服务后执行,比如给目标服务的响应添加头信息,收集统计数据等功能

    • error

      请求在其他阶段发生错误时执行

  • 生命周期

在这里插入图片描述

  • 自定义过滤器

    • 过滤器类
    /**
     * @author: jihongye
     * @date: 2021/03/07/22:18
     * @description: 路由转发之前打印日志信息
     */
    @Component
    public class PreLogFilter extends ZuulFilter {
        private Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    
        /**
         * 过滤器类型,有pre、routing、post、error四种。
         */
        @Override
        public String filterType() {
            return "pre";
        }
    
        /**
         * 过滤器执行顺序,数值越小优先级越高。
         */
        @Override
        public int filterOrder() {
            return 1;
        }
    
        /**
         * 是否进行过滤,返回true会执行过滤。
         */
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        /**
         * 自定义的过滤器逻辑,当shouldFilter()返回true时会执行。
         */
        @Override
        public Object run() throws ZuulException {
            RequestContext requestContext = RequestContext.getCurrentContext();
            HttpServletRequest request = requestContext.getRequest();
            String host = request.getRemoteHost();
            String method = request.getMethod();
            String uri = request.getRequestURI();
            LOGGER.info("Remote host:{},method:{},uri:{}", host, method, uri);
            return null;
        }
    }
    
    • 测试使用
    # 访问:http://localhost:8888/userService/get/1
    
    # 控制台打印
    com.macro.cloud.filter.PreLogFilter: Remote host:,method:GET,uri:/userService/get/1
    
  • 核心过滤器

    过滤器名称过滤类型优先级过滤器的作用
    ServletDetectionFilterpre-3检测当前请求是通过DispatcherServlet处理运行的还是ZuulServlet运行处理的。
    Servlet30WrapperFilterpre-2对原始的HttpServletRequest进行包装。
    FormBodyWrapperFilterpre-1将Content-Type为application/x-www-form-urlencoded或multipart/form-data的请求包装成FormBodyRequestWrapper对象。
    DebugFilterroute1根据zuul.debug.request的配置来决定是否打印debug日志。
    PreDecorationFilterroute5对当前请求进行预处理以便执行后续操作。
    RibbonRoutingFilterroute10通过Ribbon和Hystrix来向服务实例发起请求,并将请求结果进行返回。
    SimpleHostRoutingFilterroute100只对请求上下文中有routeHost参数的进行处理,直接使用HttpClient向routeHost对应的物理地址进行转发。
    SendForwardFilterroute500只对请求上下文中有forward.to参数的进行处理,进行本地跳转。
    SendErrorFilterpost0当其他过滤器内部发生异常时的会由它来进行处理,产生错误响应。
    SendResponseFilterpost1000利用请求上下文的响应信息来组织请求成功的响应内容。
  • 禁用过滤器

    zuul:
      filterClassName:
        filter:
          disable: true 
    
    # 禁用PreLogFilter的示例配置
    zuul:
      PreLogFilter:
        pre:
          disable: true 
    

六、常用配置

由于Zuul自动集成了Ribbon和Hystrix,所以Zuul天生就有负载均衡和服务容错能力,我们也可以通过Ribbon和Hystrix的配置来配置Zuul中的相应功能。

  • ribbon的配置

    ribbon:
      # 服务请求连接超时时间(毫秒)
      ConnectTimeout: 1000 
      # 服务请求处理超时时间(毫秒)
      ReadTimeout: 3000 
    
  • hystrix的配置

    hystrix:
      command: 
        default:
          execution:
            isolation:
              thread:
                # 配置HystrixCommand执行的超时时间,执行超过该时间会进行服务降级处理
                timeoutInMilliseconds: 1000 
    
  • zuul的配置

    zuul:
      # 路由配置  
      routes:
        user-service:
          path: /userService/**
        feign-service:
          path: /feignService/**
      # 关闭默认路由配置    
      ignored-services: user-service,feign-service 
      # 给网关路由添加前缀
      prefix: /proxy 
      # 配置过滤敏感的请求头信息,设置为空就不会过滤
      sensitive-headers: Cookie,Set-Cookie,Authorization 
      # 设置为true重定向是会添加host请求头
      add-host-header: true 
      # 关闭重试机制
      retryable: true 
      # 控制是否启用过滤器
      PreLogFilter:
        pre:
          disable: false 
    

【源码地址】:GitHub

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程小吉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值