小言_互联网的博客

【云原生&微服务>SCG网关篇八】Spring Cloud Gateway三种自定义Filter、GlobalFilter的方式

415人阅读  评论(0)

一、前言

至此微服务网关系列文章已出:

  1. 【云原生&微服务>SCG网关篇一】为什么要有网关、生产环境如何选择网关
  2. 云原生&微服务>SCG网关篇二】生产上那些灰度发布方式
  3. 【云原生&微服务>SCG网关篇三】Spring Cloud Gateway是什么、详细使用案例
  4. 云原生&微服务>SCG网关篇四】Spring Cloud Gateway内置的11种PredicateFactory如何使用
  5. 【云原生&微服务>SCG网关篇五】Spring Cloud Gateway自定义PredicateFactory
  6. 【云原生&微服务>SCG网关篇六】Spring Cloud Gateway内置的18种Filter使用姿势
  7. 【云原生&微服务>SCG网关篇六】Spring Cloud Gateway基于内置Filter实现限流、熔断、重试

聊了以下问题:

  1. 为什么要有网关?网关的作用是什么?
  2. 网关的分类?
  3. 网关的技术选型?
  4. 使用网关时常用的灰度发布方式有哪些?
  5. Spring Cloud Gateway是什么?详细使用案例?
  6. Spring Cloud Gateway内置的11种PredicateFactory
  7. 如何自定义PredicateFactory?
  8. Spring Cloud Gateway内置的18种常用的Filter
  9. Spring Cloud Gateway基于内置Filter实现限流、熔断、重试

本文接着聊Spring Cloud Gateway如何自定义Filter、GlobalFilter

PS:SpringCloud版本信息:

<properties>
    <spring-boot.version>2.4.2</spring-boot.version>
    <spring-cloud.version>2020.0.1</spring-cloud.version>
    <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--整合spring cloud-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--整合spring cloud alibaba-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

 

二、自定义Filter

GatewayFilterFactory仅能作用于单个路由Route。下面自定义一个Filter实现日志记录的功能;

1、继承自AbstractNameValueGatewayFilterFactory实现日志记录功能

1> AbstractNameValueGatewayFilterFactory子类MyLogNameValueGatewayFilterFactory:

package com.saint.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 统一日志记录Filter
 * 继承自AbstractNameValueGatewayFilterFactory,内置了两个参数:name和value;
 *
 * @author Saint
 */
@Component
@Slf4j
public class MyLogNameValueGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
   
    @Override
    public GatewayFilter apply(NameValueConfig config) {
   
        return ((exchange, chain) -> {
   
            // Filter的前置处理Prev
            log.info("MyLogGatewayFilterFactory [Pre] Filter Request, config.getName() = " + config.getName());
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
   
                // 在then方法中是请求执行结束之后的后置处理,即Filter的POST
                log.info("MyLogGatewayFilterFactory [Post] Response Filter");
            }));
        });
    }
}

 

2> application.yml中给Route配置Filter:

server:
  port: 9999
spring:
  cloud:
    gateway:
      routes:
        - id: add_request_parameter_route
          uri: http://127.0.0.1:9001
          predicates:
            - Path=/**
          filters:
            # 自定义过滤器的名字,即:MyLogNameValueGatewayFilterFactory
            - name: MyLogNameValue
              args:
                name: Saint_name
                value: Saint_value

 

3> 测试:

访问接口:http://127.0.0.1:9999/hello/sayHello,看gateway-center控制台输出如下:

2、继承自AbstractGatewayFilterFactory实现日志记录功能

当我们想要对Filter指定一些别的参数时,就可以通过继承自AbstractGatewayFilterFactory来实现。

1> AbstractGatewayFilterFactory子类MyLogGatewayFilterFactory:

package com.saint.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 统一日志记录Filter
 * AbstractGatewayFilterFactory,可以自定义参数;
 *
 * @author Saint
 */
@Component
@Slf4j
public class MyLogGatewayFilterFactory extends AbstractGatewayFilterFactory<MyLogGatewayFilterFactory.MyConfig> {
   

    public MyLogGatewayFilterFactory() {
   
        super(MyConfig.class);
    }

    @Override
    public GatewayFilter apply(MyConfig config) {
   
        return ((exchange, chain) -> {
   
            // Filter的前置处理Prev
            log.info("MyLogGatewayFilterFactory [Pre] Filter Request, config.getName() = " + config.getName());
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
   
                // 在then方法中是请求执行结束之后的后置处理,即Filter的POST
                log.info("MyLogGatewayFilterFactory [Post] Response Filter");
            }));
        });
    }


    /**
     * MyConfig只是一个配置类,该类中只有一个属性name。这个属性可以在yml文件中使用
     */
    public static class MyConfig {
   
        private String name;

        public String getName() {
   
            return name;
        }

        public void setName(String name) {
   
            this.name = name;
        }
    }
}

 

2> application.yml中给Route配置Filter:

server:
  port: 9999
spring:
  cloud:
    gateway:
      routes:
        - id: add_request_parameter_route
          uri: http://127.0.0.1:9001
          predicates:
            - Path=/**
          filters:
            # 自定义过滤器的名字,即:MyLogGatewayFilterFactory
            - name: MyLog
              args:
                name: Saint_log_name

3> 测试:

访问接口:http://127.0.0.1:9999/hello/sayHello,看gateway-center控制台输出如下:

三、自定义GlobalFilter

GlobalFilter会作用于所有的路由Route。下面自定义一个GlobalFilter实现网关层面的鉴权功能;

1、自定义GlobalFilter实现鉴权功能

1> GlobalFilter实现类AuthFilter:

package com.saint.gateway.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 对所有路由生效的GlobalFilter,鉴权使用
 *
 * @author Saint
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
   
    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    @Value("#{'${auth.skip.urls:}'.split(',')}")
    private List<String> skipAuthUrls;

    /**
     * 存放token信息的请求头属性
     */
    public static final String COOKIE_NAME_TOKEN = "saint_token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
   
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //3.判断 是否需要直接放行
        logger.info("uri: {}", request.getURI());
        if (skipAuthUrls.contains(request.getURI().toString())) {
   
            return chain.filter(exchange);
        }

        //4 校验
        //4.1 从头header中获取令牌数据
        String token = request.getHeaders().getFirst(COOKIE_NAME_TOKEN);

        if (StringUtils.isEmpty(token)) {
   
            //4.2 从cookie中中获取令牌数据
            HttpCookie first = request.getCookies().getFirst(COOKIE_NAME_TOKEN);
            if (first != null) {
   
                token = first.getValue();//就是令牌的数据
            }
        }

        if (StringUtils.isEmpty(token)) {
   
            //4.3 从请求参数中获取令牌数据
            token = request.getQueryParams().getFirst(COOKIE_NAME_TOKEN);
        }

        if (StringUtils.isEmpty(token)) {
   
            //4.4. 如果没有数据    没有登录,要重定向到登录到页面
            response.setStatusCode(HttpStatus.FORBIDDEN);//403
            // 4.5. 在响应头里添加鉴权失败信息
            response.getHeaders().set("auth_error", "xxxx");
            return response.setComplete();
        }


        //TODO 5 解析令牌数据 ( 判断解析是否正确,正确 就放行 ,否则 结束)

        try {
   

            logger.info("authed user info: {}", "*****");
        } catch (Exception e) {
   
            logger.error("parse token error:", e);
            //解析失败
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }

        // 6 将token添加到头信息,传递给后续的服务
        request.mutate().header(COOKIE_NAME_TOKEN, token);
        return chain.filter(exchange);
    }

    /**
     * 这里表示将当前Filter放在过滤链的最前面
     *
     * @return
     */
    @Override
    public int getOrder() {
   
        return 0;
    }
}

 

AuthFilter不仅实现了GlobalFilter对所有的Route进行过滤操作,还要实现Ordered接口,并重写getORder()方法返回0,表示最先执行当前AuthFilter。

2> pom.xml中引入commons-lang3:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

3> application.yml文件中设置不走鉴权的URI:

auth:
  skip:
    urls: http://localhost:9001/service-a/hello, http://localhost:9001/service-b/hello

四、总结

本文我们聊了三种自定义Filter / GlobalFilter的方式,分别为:继承AbstractNameValueGatewayFilterFactory、继承AbstractGatewayFilterFactory、实现GlobalFilter接口。下文接着聊Spring Cloud Gateway 和Nacos的集成。


转载:https://blog.csdn.net/Saintmm/article/details/125829255
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场