【1.3 API服务网关(SpringCloudGateway)】Spring Cloud Gateway网关自定义拦截器实现鉴权
在Spring Cloud Gateway中,可以通过实现GatewayFilterFactory
接口来创建自定义的拦截器。以下是一个简单的自定义拦截器的例子,它会在请求被路由之前打印一条日志。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class CustomGatewayFilterFactory implements GatewayFilterFactory, Ordered {
private static final Logger log = LoggerFactory.getLogger(CustomGatewayFilterFactory.class);
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
log.info("Custom Gateway Filter Factory is called. Config: {}", config.toString());
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("Request is routed successfully");
}));
};
}
@Override
public int getOrder() {
// 定义拦截器的顺序,数字越小,优先级越高
return 0;
}
}
在application.yml
配置文件中添加自定义拦截器:
spring:
cloud:
gateway:
routes:
- id: custom_route
uri: https://example.org
filters:
- CustomGatewayFilterFactory=someConfig
在这个例子中,CustomGatewayFilterFactory
是自定义的拦截器工厂,它实现了GatewayFilterFactory
接口。在路由配置中,通过CustomGatewayFilterFactory
指定了一个配置参数someConfig
。当请求通过网关时,它会先经过自定义拦截器打印日志,然后再路由到指定的服务。
评论已关闭