欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

10 Gateway自定义过滤器

程序员文章站 2022-07-02 19:12:17
自定义局部过滤器自定义局部过滤器;继承AbstractGatewayFilterFactoryserver: port: 10010spring: application: name: api-gateway cloud: gateway: routes: # 路由id,可以任意 - id: user-service-route # 代理的服务地址 #uri: http://127.0.0....

自定义局部过滤器

自定义局部过滤器;继承AbstractGatewayFilterFactory

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # 路由id,可以任意
        - id: user-service-route
          # 代理的服务地址
          #uri: http://127.0.0.1:9090
          # lb表示从eureka中获取具体服务 ;lb 之后编写的服务名必须要在eureka中注册才能使用
          uri: lb://UserService
          # 路由断言: 可以匹配映射路径
          predicates:
            #- Path=/UserController/**
            #- Path=/**
            - Path=/api/UserController/**
          filters:
            #1表示过滤1个路径,2表示两个路径,以此类推
            - StripPrefix=1
            - #自定义过滤器  :  名称  + GatewayFilterFactory就是类名称了
            - MyParam=name
      # 默认过滤器,对所有的路由都生效(全局)
      default-filters:
        - AddResponseHeader=X-Response-Foo,Bar
        - AddResponseHeader=x-myname,itcast

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
    instance:
      prefer-ip-address: true

自定义过滤器
MyParamGatewayFilterFactory --》yml中的MyParam

package li.chen.com.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: MyParamGatewayFilterFactory
 * @Description 自定义过滤器
 **/
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {
    static final String PARAM_NAME = "param";

    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }


    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // http://127.0.0.1:9090/UserController/1   config.param ==> name
            //获取请求参数中param对应的参数名 的参数值
            ServerHttpRequest request = exchange.getRequest();
            if (request.getQueryParams().containsKey(config.param)) {
                request.getQueryParams().get(config.param).
                        forEach(value -> System.out.printf("------------局部过滤器--------%s = %s------", config.param, value));
            }
            return chain.filter(exchange);
        };
    }

    public static class Config {
        //对应在配置过滤器的时候指定的参数名
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}

运行启动类

package li.chen.com.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class,args);
    }
}

测试结果:
http://127.0.0.1:10010/api/UserController/1?name=zzz
报错!!!

Caused by: reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name MyParam
Caused by: java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name MyParam

10 Gateway自定义过滤器
10 Gateway自定义过滤器

自定义全局过滤器

无需配置yml,直接编写继承GlobalFilter就可以

package li.chen.com.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName: MyGlobalFilter
 * @Description 全局过滤器
 **/
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("--------------全局过滤器MyGlobalFilter------------------");
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if(StringUtils.isBlank(token)){
            //设置响应状态码为未授权
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //值越小越先执行
        return 1;
    }
}

测试:
访问 http://127.0.0.1:10010/api/UserController/7 页面返回401,无权限
访问 http://127.0.0.1:10010/api/UserController/7?token=aaa 返回正常数据

本文地址:https://blog.csdn.net/cl66666666/article/details/113844623

相关标签: springcloud