springcloud Gateway 自定义过滤器例子

springcloud Gateway网关自定义过滤器类型主要分全局和指定路由两种:
   GlobalFilter:全局过滤器,对所有的路由均起作用
   GatewayFilter:只对指定的路由起作用

GatewayFilter又有两种实现方式:
一种是直接 实现GatewayFilter, Ordered接口,另一种是 继承AbstractGatewayFilterFactory类
实现GatewayFilter, Ordered接口方式过滤器:

@Component
public class SignFilter implements GatewayFilter, Ordered {

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getResponse().setStatusCode(HttpStatus.OK);
        //exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ApiResponse result = new ApiResponse();
        
        String sign = exchange.getRequest().getQueryParams().getFirst("sign");
        if(StringUtils.isEmpty(sign)) {
            result.setCode("99");
            result.setMessage("签名验证失败");
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(JsonUtil.objToJsonBytes(result));
            return exchange.getResponse().writeWith(Flux.just(dataBuffer));
        }
        return chain.filter(exchange);
    }

    /**过滤器群执行顺序
     * 值越大则优先级越低
     * */
    @Override
    public int getOrder() {
        return 0;
    }
  
}

注入bean:

@SpringBootApplication
public class GateWayApplicationMain {

    public static void main(String[] args) {
        SpringApplication.run(GateWayApplicationMain.class, args);
    }
    
    /**自定义过滤器有两种实现方式*/
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes().route(r ->
                r.path("/sys/**")
                .uri("http://localhost:6320")
                .filters(new SignFilter())
                .id("apiweb"))
            .build();
    }
    
}

 

你可能感兴趣的:(springcloud)