Spring Cloud Gateway 自定义过滤器 filter
- CheckAuth=lisi
server: port: 8060 spring: application: name: api-gateway cloud: # gateway的配置 gateway: # 路由规则 routes: - id: order_route # 路由的唯一标识, 路由到 order # uri: http://localhost:8020 # 需要转发的地址 uri: lb://order-nacos-service # 需要转发的地址 lb:使用nacos中的本地负载均衡策略 # 断言规则 用于路由规则的匹配 predicates: - Path=/order-serv/** # http://localhost:8060/order-serv/order/add 路由转到 # http://localhost:8020/order-serv/order/add # - After=2017-01-20T17:42:47.789-07:00[Asia/Shanghai] # - Header=X-Request-Id,\d+ # - Method=GET # - Query=name,zhangsan|lisi # - CheckAuth=lisi filters: - StripPrefix=1 # 转发之前去掉第一层路径 # http://localhost:8020/order-serv/order/add 过虑成 # http://localhost:8020/order/add # - AddRequestHeader=X-Request-color, blue # - AddRequestParameter=color, red - PrefixPath=/mall-order #添加前缀, 对应微服务需要配置context-path # - RedirectTo=302, https://www.baidu.com/ #重定向到百度 # - SetStatus=404 - CheckAuth=lisi # 配置 Nacos nacos: server-addr: 127.0.0.1:8848 discovery: # server-addr: 127.0.0.1:8848 username: nacos password: nacos namespace: public
package com.wsm.filters; import org.apache.commons.lang.StringUtils; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; @Component public class CheckAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CheckAuthGatewayFilterFactory.Config> { public CheckAuthGatewayFilterFactory(){ super(CheckAuthGatewayFilterFactory.Config.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList("name"); } @Override public GatewayFilter apply(CheckAuthGatewayFilterFactory.Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //获取name参数 String name = exchange.getRequest().getQueryParams().getFirst("name"); System.out.println("============"+name); if(StringUtils.isNotBlank(name)){ if(config.getName().equals(name)){ return chain.filter(exchange); }else{ //返回404 exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); return exchange.getResponse().setComplete(); } } //正常请求 return chain.filter(exchange); } }; } public static class Config { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } }