我有一个 Spring Cloud Gateway 应用程序。我正在尝试设置网关过滤器。 Spring Boot 版本是
2.3.4.RELEASE
以下是依赖项:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation platform(SpringBootPlugin.BOM_COORDINATES)
implementation platform('org.springframework.cloud:spring-cloud-dependencies:Hoxton.SR8')
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.cloud:spring-cloud-starter-sleuth'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
}
这是网关客户端的配置
server:
port: 8081
spring:
cloud:
gateway:
routes:
- id: onboard_redirect
uri: http://localhost:8080/api/v1/onboard
predicates:
- Path=/api/v1/onboard
filters:
- name: MyLogging
args:
baseMessage: My Custom Message
preLogger: true
postLogger: true
这是我的过滤器类:
@Component
public class MyLoggingGatewayFilterFactory extends AbstractGatewayFilterFactory<MyLoggingGatewayFilterFactory.Config> {
final Logger logger =
LoggerFactory.getLogger(MyLoggingGatewayFilterFactory.class);
public MyLoggingGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
// Pre-processing
if (config.preLogger) {
logger.info("Pre GatewayFilter logging: "
+ config.baseMessage);
}
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
// Post-processing
if (config.postLogger) {
logger.info("Post GatewayFilter logging: "
+ config.baseMessage);
}
}));
};
}
public static class Config {
public String baseMessage;
public boolean preLogger;
public boolean postLogger;
}
}
无需配置过滤器,一切正常,但当我配置过滤器时,出现以下错误:
reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name MyLogging
Caused by: java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name MyLogging
我在这里做错了什么?
过滤器类别是
MyLoggingGatewayFilterFactory
,而不是您在属性中设置的 MyLogging
。
尝试在您的
application.yml
文件中进行以下修改:
filters:
- name: MyLoggingGatewayFilterFactory
仔细检查您的 Spring 组件扫描是否正在为您的特定过滤器类拾取
@Component
注释。默认情况下,Spring 只会选取您的 @SpringBootApplication
包下的过滤器,因此,如果您的过滤器位于单独的基础包下,您可能需要显式告诉组件扫描包含该包。
例如,
@SpringBootApplication
@ComponentScan({"com.myapp", "com.myfilters"})
public class MyApp {
根据 spring 文档,自定义过滤器类不需要@Component。
https://cloud.spring.io/spring-cloud-gateway/reference/html/#writing-custom-gatewayfilter-factories
在 application.properties 文件中添加此依赖项。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-
resilience4j</artifactId>
</dependency>