Gateway网关---Filter过滤器

官网关于过滤器的文档地址https://cloud.spring.io/spring-cloud-gateway/2.2.x/reference/html/#gatewayfilter-factories

过滤请求头包含参数 X-Request-red 并且值是blue的

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue

自定义过滤器

创建一个类实现GlobalFilterOrdered接口
可以通过exchange获取请求的RequestResponse对象,然后获取其中的内容,进行判断过滤,然后加入到chain中即可

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;

@Component
public class MyGatewayFilter implements GlobalFilter, Ordered {
     
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
     
        String name = exchange.getRequest().getQueryParams().getFirst("name");
        if (name==null){
     
            System.out.println("用户名为null");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        chain.filter(exchange);
        return null;
    }

    @Override
    public int getOrder() {
     
        return 0;
    }
}

你可能感兴趣的:(#,gateway)