springcloud Gateway 自定义过滤器例子
发布日期:2021-09-18 00:51:44 浏览次数:11 分类:技术文章

本文共 1653 字,大约阅读时间需要 5 分钟。

springcloud Gateway网关自定义过滤器类型主要分全局和指定路由两种:

   GlobalFilter:全局过滤器,对所有的路由均起作用
   GatewayFilter:只对指定的路由起作用

GatewayFilter又有两种实现方式:

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

@Componentpublic 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:

@SpringBootApplicationpublic 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();    }    }

 

转载地址:https://blog.csdn.net/yucaifu1989/article/details/105102560 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:springcloud gateway 获取post请求体Json分段导致不全的解决方案
下一篇:Spring Cloud 系列之 Spring cloud gateway 实现网关路由转发和过滤功能

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年03月26日 10时03分18秒